<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="计划单号" prop="planNumber">
        <el-input
          v-model="queryParams.planNumber"
          placeholder="请输入采购单号"
          clearable
          @keyup.enter.native="getList"
        />
      </el-form-item>
      <el-form-item label="采购日期" prop="planDate">
        <el-date-picker
          clearable
          v-model="queryParams.planDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择采购日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="计划状态" prop="planStatus">
        <el-select
          v-model="queryParams.planStatus"
          placeholder="请选择计划状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.tb_procured_plan"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="getList"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['procured:plan:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="SelectedHandleUpdate"
          v-hasPermi="['procured:plan:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="selectedHandleDelete"
          v-hasPermi="['procured:plan:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5" v-if="1 == 2">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['procured:plan:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-folder-checked"
          size="mini"
          @click="underReview"
          v-hasPermi="['procured:plan:approved']"
          >审核</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          size="mini"
          icon="el-icon-s-opportunity"
          :disabled="single"
          @click="handleAudit"
          v-hasPermi="['procured:plan:revoke']"
          >撤回</el-button
        >
      </el-col>
      <el-col :span="1.5" v-if="1 == 2">
        <el-button
          type="primary"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleApproved"
          v-hasPermi="['procured:plan:approved']"
          >核准</el-button
        >
      </el-col>
      <el-col :span="1.5" v-if="1 == 2">
        <el-button
          type="danger"
          plain
          icon="el-icon-close"
          size="mini"
          :disabled="multiple"
          @click="handleApp"
          v-hasPermi="['procured:plan:approved']"
          >反核准</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="planList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="采购计划号"
        align="center"
        prop="planNumber"
        min-width="180"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.planNumber">{{ scope.row.planNumber }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人/创建日期" align="center" min-width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.userName">{{ scope.row.userName }}</span>
          <span v-else>-</span>
          <br />
          <span v-if="scope.row.addTime">{{
            parseTime(scope.row.addTime, "{y}-{m}-{d}")
          }}</span>
          <span v-else>-</span>
          <span v-if="scope.row.addTime"
            >&nbsp;{{ parseTime(scope.row.addTime, "{h}:{i}") }}</span
          >
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="计划状态"
        align="center"
        prop="planStatus"
        min-width="180"
      >
        <template slot-scope="scope">
          <span
            v-if="
              scope.row.planStatus !== null &&
              scope.row.planStatus !== undefined
            "
          >
            <dict-tag
              :options="dict.type.tb_procured_plan"
              :value="scope.row.planStatus"
            />
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        align="center"
        prop="planRemark"
        min-width="180"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.planRemark"
            >{{ scope.row.planRemark.slice(0, 10) }}
            <span v-if="scope.row.planRemark.length > 10">...</span>
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="采购日期"
        align="center"
        prop="planDate"
        min-width="180"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.planDate">{{
            parseTime(scope.row.planDate, "{y}-{m}-{d}")
          }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="采购金额"
        align="center"
        prop="actualAmount"
        min-width="180"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.actualAmount">{{
            scope.row.actualAmount
          }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="总件数"
        align="center"
        prop="total"
        min-width="180"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.total">{{ scope.row.total }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="仓库"
        align="center"
        prop="warehouseName"
        min-width="180"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.warehouseName">{{
            scope.row.warehouseName
          }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="部门"
        align="center"
        prop="deptName"
        min-width="180"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.deptName">{{ scope.row.deptName }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="核准人/核准日期" align="center" min-width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.approver">{{ scope.row.approver }}</span>
          <span v-else>-</span>
          <br />
          <span v-if="scope.row.approvedTime">{{
            parseTime(scope.row.approvedTime, "{y}-{m}-{d}")
          }}</span>
          <span v-else>-</span>
          <span v-if="scope.row.approvedTime"
            >&nbsp;{{ parseTime(scope.row.approvedTime, "{h}:{i}") }}</span
          >
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="180"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="[
              'procured:plan:edit',
              'procured:plan:remove',
              'procured:plan:batch',
            ]"
          >
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right"
              >更多</el-button
            >
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-if="scope.row.planStatus == 0"
                command="handleUpdate"
                icon="el-icon-edit"
                v-hasPermi="['procured:plan:edit']"
              >
                修改
              </el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.planStatus == 0"
                command="handleDelete"
                icon="el-icon-delete"
                v-hasPermi="['procured:plan:remove']"
              >
                删除
              </el-dropdown-item>
              <!-- 分批下单按钮 -->
              <el-dropdown-item
                command="handleBatch"
                icon="el-icon-document-checked"
                v-hasPermi="['procured:plan:batch']"
                v-if="
                  (scope.row.planStatus != 0) &
                  (scope.row.planStatus != 3) &
                  (scope.row.planStatus != 4) &
                  (scope.row.planStatus != 5)
                "
              >
                分批下单
              </el-dropdown-item>
              <el-dropdown-item
                command="handleDetails"
                icon="el-icon-document"
                v-hasPermi="['procured:plan:query']"
                v-if="scope.row.planStatus == 3"
              >
                详情
              </el-dropdown-item>
              <!-- 查看按钮 -->
              <el-dropdown-item
                command="handleViewProducts"
                icon="el-icon-view"
                v-hasPermi="['procured:plan:query']"
              >
                查看
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购计划对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="90%"
      append-to-body
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="基础信息" name="first">
            <el-row>
              <el-col :span="6">
                <el-form-item label="计划单号" prop="planNumber">
                  <el-input
                    v-model="form.planNumber"
                    :disabled="true"
                    placeholder="自动生成"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购日期" prop="planDate">
                  <el-date-picker
                    clearable
                    v-model="form.planDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择采购日期"
                    :default-value="new Date().toISOString().split('T')[0]"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购公司" prop="companyId">
                  <treeselect
                    v-model="form.companyId"
                    :options="companyOptions"
                    :show-count="true"
                    placeholder="请输入采购公司"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购部门" prop="deptName">
                  <el-input
                    v-model="form.deptName"
                    placeholder="请输入采购部门"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="采购人员" prop="userName">
                  <el-input
                    v-model="form.userName"
                    placeholder="请输入采购人员"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="预入仓库" prop="warehouseId">
                  <treeselect
                    v-model="form.warehouseId"
                    :options="warehouseOptions"
                    :show-count="true"
                    placeholder="请输入预入仓库"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="销售计划" prop="salesPlanNumber">
                  <el-input
                    v-model="form.salesPlanNumber"
                    placeholder="请输入销售计划"
                    :disabled="true"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-button
                  round
                  @click="handleSalesPlan"
                  :disabled="this.viewMode || this.isEdit"
                  style="margin-left: 10px"
                  >选择销售计划</el-button
                >
              </el-col>
            </el-row>
            <!-- 隐藏的输入字段 -->
            <el-input type="hidden" v-model="form.salesPlanId"></el-input>
            <el-row>
              <el-col :span="24">
                <el-form-item label="交货地址" prop="deliveryAddress">
                  <el-input
                    v-model="form.deliveryAddress"
                    placeholder="请输入交货地址"
                    type="textarea"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="planRemark">
                  <el-input
                    v-model="form.planRemark"
                    placeholder="请输入备注"
                    type="textarea"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-divider content-position="center">信息</el-divider>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  v-show="!viewMode"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAddTbProcuredProduct"
                  >添加</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  v-show="!viewMode"
                  icon="el-icon-delete"
                  size="mini"
                  @click="handleDeleteTbProcuredProduct"
                  >删除</el-button
                >
              </el-col>
            </el-row>
            <el-table
              :data="tbProcuredProductList"
              :row-class-name="rowTbProcuredProductIndex"
              @selection-change="handleTbProcuredProductSelectionChanges"
              ref="tbProcuredProduct"
              v-loading="loading"
              height="600px"
              width="100%"
              :span-method="tableSpanMethod"
              :row-key="(row) => row.productId"
            >
              <el-table-column
                type="selection"
                min-width="50"
                align="center"
                :selectable="
                  (row) => row.returnCompletedStatus !== 1 && row.returnCompletedStatus !== '1'
                "
                :disabled="viewMode"
              />
              <el-table-column
                label="序号"
                align="center"
                prop="index"
                min-width="50"
              />
              <el-table-column
                label="图片"
                prop="imgName"
                align="center"
                min-width="100"
              >
                <template slot-scope="scope">
                  <div class="image-container">
                    <image-preview
                      v-for="(image, index) in scope.row.imgName"
                      :key="index"
                      :src="image"
                      :width="50"
                      :height="50"
                      class="image-item"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="产品名称"
                prop="productName"
                align="center"
                min-width="150"
              >
              </el-table-column>
              <el-table-column
                label="SKU"
                prop="sku"
                align="center"
                min-width="150"
              >
              </el-table-column>
              <el-table-column
                label="GTIN"
                prop="gtin"
                align="center"
                min-width="150"
              >
              </el-table-column>
              <el-table-column
                label="采购数量"
                prop="number"
                align="center"
                min-width="100"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.number"
                    :disabled="viewMode"
                    size="small"
                  />
                </template>
              </el-table-column>
              <!-- 合计数量列 -->
              <el-table-column
                label="合计数量"
                prop="totalQuantity"
                align="center"
                min-width="100"
              >
                <template slot-scope="scope">
                  <!-- 根据当前行的 sku 去计算属性 skuNumberSums 里取值 -->
                  <span>{{ skuNumberSums[scope.row.sku] }}</span>
                </template>
              </el-table-column>

              <el-table-column label="单价" prop="productPrice" min-width="100">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.productPrice"
                    :disabled="viewMode"
                    placeholder="请输入单价"
                    @input="handleRateChangeRow(scope.row)"
                  />
                </template>
              </el-table-column>
              <!-- 货币单位列 -->
              <el-table-column
                label="货币单位"
                prop="monetaryId"
                min-width="100"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.monetaryId"
                    :disabled="viewMode"
                    placeholder=""
                    @change="handleCurrencyChangeRow(scope.row)"
                  >
                    <el-option
                      v-for="item in monetaryOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>

              <!-- 新增每个产品的汇率输入 -->
              <el-table-column label="汇率" prop="currency" min-width="100">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.currency"
                    :disabled="scope.row.currencyDisabled || viewMode"
                    placeholder=""
                    @input="handleRateChangeRow(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="金额(¥)"
                prop="amount"
                align="center"
                min-width="150"
              >
                <template slot-scope="scope">
                  <!-- 判断是否是该 sku 分组的起始行 -->
                  <span
                    v-if="
                      skuGroups[scope.row.sku] &&
                      scope.$index === skuGroups[scope.row.sku].start
                    "
                  >
                    <!-- 如果是第一行，显示合计值 -->
                    {{ skuAggregates[scope.row.sku].amountSum.toFixed(2) }}
                  </span>
                  <span v-else> - </span>
                </template>
              </el-table-column>

              <el-table-column
                label="税率(%)"
                prop="rate"
                align="center"
                min-width="100"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.rate"
                    :disabled="viewMode"
                    placeholder="请输入税率"
                    @input="handleRateChangeRow(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="税额(¥)"
                prop="tax"
                align="center"
                min-width="150"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      skuGroups[scope.row.sku] &&
                      scope.$index === skuGroups[scope.row.sku].start
                    "
                  >
                    {{ skuAggregates[scope.row.sku].taxSum.toFixed(2) }}
                  </span>
                </template>
              </el-table-column>

              <el-table-column
                label="含税金额(¥)"
                prop="taxIncluded"
                align="center"
                min-width="150"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      skuGroups[scope.row.sku] &&
                      scope.$index === skuGroups[scope.row.sku].start
                    "
                  >
                    {{ skuAggregates[scope.row.sku].taxIncludedSum.toFixed(2) }}
                  </span>
                </template>
              </el-table-column>

              <!-- 新增每个产品的运费输入 -->
              <el-table-column label="运费" prop="freight" min-width="120">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.freight"
                    :disabled="
                      scope.row.flag ||
                      isDisabledByVendor(scope.row) ||
                      viewMode
                    "
                    placeholder=""
                    @change="handleFreightBlur(scope.row)"
                  />
                </template>
              </el-table-column>
              <!-- 新增每个产品的供应商付勾选 -->
              <el-table-column label="供应商付" prop="flag" min-width="100">
                <template slot-scope="scope">
                  <el-checkbox
                    v-model="scope.row.flag"
                    :disabled="isDisabledByVendor(scope.row) || viewMode"
                    @change="onSupplierPaysChangeRow(scope.row)"
                    >供应商付</el-checkbox
                  >
                </template>
              </el-table-column>
              <!-- 新增总成本列：含税金额+运费 -->
              <el-table-column label="总成本(¥)" align="center" min-width="100">
                <template slot-scope="scope">
                  <span
                    v-if="
                      skuGroups[scope.row.sku] &&
                      scope.$index === skuGroups[scope.row.sku].start
                    "
                  >
                    {{ skuAggregates[scope.row.sku].totalCostSum.toFixed(2) }}
                  </span>
                </template>
              </el-table-column>

              <el-table-column label="供应商" prop="vendorId" min-width="270">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.orderNo1688"
                    :disabled="viewMode"
                    placeholder="请输入1688订单号"
                    clearable
                    style="margin-bottom: 8px"
                  />
                  <el-select
                    v-model="scope.row.vendorId"
                    :disabled="viewMode"
                    placeholder=""
                    filterable
                    size="medium"
                    @change="handleVendorChangeRow(scope.row)"
                    style="min-width: 250px"
                  >
                    <el-option
                      v-for="item in vendorOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                label="交付时间"
                prop="deliveryTime"
                min-width="230"
              >
                <template slot-scope="scope">
                  <el-date-picker
                    :disabled="viewMode"
                    v-model="scope.row.deliveryTime"
                    type="datetime"
                    placeholder=""
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column
                label="备注"
                prop="productRemark"
                min-width="200"
              >
                <template slot-scope="scope">
                  <el-input
                    type="textarea"
                    v-model="scope.row.productRemark"
                    size="small"
                    placeholder="请输入备注"
                    :disabled="viewMode"
                    clearable
                  />
                </template>
              </el-table-column>
            </el-table>
            <!-- 添加一个总成本显示区域 -->
            <div style="margin-top: 20px; text-align: right; font-size: 16px">
              <strong>总成本(¥): </strong>
              <span>{{ procuredPlanTotalCost.toFixed(2) }}</span>
            </div>
          </el-tab-pane>
          <el-tab-pane label="合同备注" name="second">
            <el-row>
              <el-col :span="24">
                <editor
                  v-model="form.contract"
                  :min-height="192"
                  ref="quillEditor"
                  :read-only="true"
                />
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          v-if="!viewMode"
          :loading="loading"
          @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加产品 -->
    <el-dialog
      :title="titleName"
      :visible.sync="productOpen"
      width="80%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        :model="queryParamProduct"
        ref="queryFormProduct"
        size="small"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="queryParamProduct.name"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter.native="handleQueryProduct"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParamProduct.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_job_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQueryProduct"
            >搜索</el-button
          >
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="resetQueryProduct"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <!-- 添加一个判断，没有数据时显示提示 -->
      <div
        v-if="!productsList.length"
        style="text-align: center; padding: 20px; color: #999"
      >
        销售计划中的产品已全部添加
      </div>
      <el-table
        v-loading="loadingProduct"
        :data="productsList"
        @selection-change="handleSelectionChanges"
        height="510px"
        ref="myTable"
        :row-key="'shipmentsId'"
      >
        <el-table-column
          type="selection"
          min-width="50"
          align="center"
          :reserve-selection="true"
        />
        <el-table-column
          label="图片"
          prop="imgName"
          align="center"
          min-width="100"
        >
          <template slot-scope="scope">
            <div class="image-container">
              <image-preview
                v-for="(image, index) in scope.row.imgName"
                :key="index"
                :src="image"
                :width="50"
                :height="50"
                class="image-item"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="名称"
          align="center"
          prop="name"
          min-width="100"
        />
        <el-table-column
          label="品牌"
          align="center"
          prop="brandName"
          min-width="100"
        />
        <el-table-column
          label="产品SKU"
          align="center"
          prop="sku"
          min-width="100"
        />
        <el-table-column
          label="单价(￥)"
          align="center"
          prop="price"
          min-width="100"
        />
        <el-table-column
          label="GTIN"
          align="center"
          prop="gtin"
          min-width="100"
        />
        <el-table-column label="计划数量" align="center" min-width="100">
          <template slot-scope="scope">
            <span>
              {{ scope.row.planSize }}个
              <span v-if="scope.row.terminatedQuantity">
                (原：{{ scope.row.terminatedQuantity + scope.row.planSize }}个)
              </span>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="已采购数量"
          align="center"
          prop="procuredSelectedCount"
          min-width="100"
        />
        <!-- <el-table-column label="未发货数量" align="center" prop="operSize" /> -->
        <el-table-column
          label="金额"
          align="center"
          prop="amount"
          min-width="100"
        />
        <el-table-column
          label="备注"
          align="center"
          prop="productRemarks"
          min-width="100"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.productRemarks">
              {{ scope.row.productRemarks.slice(0, 10) }}
              <span v-if="scope.row.productRemarks.length > 10">...</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <!-- 操作列中的按钮 -->
            <el-button
              v-show="!tempSelectedShipmentIds.includes(scope.row.shipmentsId)"
              @click="toggleSelectProduct(scope.row)"
              size="small"
              >选择</el-button
            >
            <el-button
              v-show="tempSelectedShipmentIds.includes(scope.row.shipmentsId)"
              @click="toggleSelectProduct(scope.row)"
              type="primary"
              size="small"
              >已选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="totalProduct > 0"
        :total="totalProduct"
        :page.sync="queryParamProduct.pageNum"
        :limit.sync="queryParamProduct.pageSize"
        @pagination="handleQueryProduct"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="submitFormProduct"
          >确 定</el-button
        >
        <el-button @click="cancelProduct">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择销售计划 -->
    <el-dialog
      :title="titleSalesPlan"
      :visible.sync="openSalesPlan"
      width="80%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        :model="queryParamPlan"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="计划编号" prop="planNumber">
          <el-input
            v-model="queryParamPlan.planNumber"
            placeholder="请输入计划编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="计划名称" prop="planName">
          <el-input
            v-model="queryParamPlan.planName"
            placeholder="请输入计划名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="planListIndex">
        <el-table-column
          label="计划编号"
          align="center"
          prop="planNumber"
          width="150px"
        />
        <el-table-column
          label="计划名称"
          align="center"
          prop="planName"
          width="170px"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.planName">
              {{ scope.row.planName.slice(0, 10) }}
              <span v-if="scope.row.planName.length > 10">...</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="发货日期" align="center" prop="shipTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.shipTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="货运方式"
          align="center"
          prop="mannerName"
          width="170px"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.mannerName">
              {{ scope.row.mannerName.slice(0, 10) }}
              <span v-if="scope.row.mannerName.length > 10">...</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="发往店铺" align="center" prop="shopName" />
        <el-table-column label="制单人" align="center" prop="nickName" />
        <el-table-column label="计划状态" align="center" prop="planStatus">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.tb_plan"
              :value="scope.row.planStatus"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="制单日期"
          align="center"
          prop="preparationTime"
          width="135"
        >
          <template slot-scope="scope">
            <span
              >{{ parseTime(scope.row.preparationTime, "{y}-{m}-{d}") }}
              {{ parseTime(scope.row.preparationTime, "{h}:{i}") }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          align="center"
          prop="remark"
          width="170px"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.remark">
              {{ scope.row.remark.slice(0, 10) }}
              <span v-if="scope.row.remark.length > 10">...</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handlePlan(scope.row)"
              v-hasPermi="['procured:plan:add']"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="totalPlan > 0"
        :total="totalPlan"
        :page.sync="queryParamPlan.pageNum"
        :limit.sync="queryParamPlan.pageSize"
        @pagination="getPlanList"
      />
    </el-dialog>

    <!-- 分批下单 -->
    <el-dialog
      :title="titleBatch"
      :visible.sync="openBatch"
      width="90%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="基础信息" name="first">
            <el-row>
              <el-col :span="6">
                <el-form-item label="计划单号:" prop="planNumber">
                  {{ form.planNumber }}
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购日期:" prop="planDate">
                  {{ form.planDate }}
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="供应商类型:"
                  prop="supplierType"
                  label-width="100px"
                >
                  <el-select
                    v-model="form.supplierType"
                    placeholder="请选择供应商类型"
                    @change="supplierTypeChange"
                  >
                    <el-option label="线下供应商" value="1"></el-option>
                    <el-option label="1688供应商" value="0"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购公司:" prop="companyName">
                  {{ form.companyName }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="采购批次:" prop="purchaseBatchNumber">
                  <el-input
                    v-model="form.purchaseBatchNumber"
                    class="custom-input"
                    placeholder="系统自动生成"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购部门:" prop="deptName">
                  {{ form.deptName }}
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购员:" prop="userName">
                  {{ form.userName }}
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="预入仓库:" prop="warehouseName">
                  {{ form.warehouseName }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="交货地址:" prop="deliveryAddress">
                  {{ form.deliveryAddress }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注:" prop="planRemark">
                  {{ form.planRemark }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item
                  label="采购订单备注:"
                  prop="purchaseOrderRemark"
                  label-width="105px"
                >
                  <el-input
                    v-model="form.purchaseOrderRemark"
                    type="textarea"
                    placeholder="请输入采购订单备注信息"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 产品选择部分 -->
            <el-divider content-position="center">信息</el-divider>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAddList(form.planId)"
                >
                  添加产品
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="handleDeleteTbProcuredProducts"
                >
                  删除
                </el-button>
              </el-col>
            </el-row>
            <el-table
              :data="batchOrderProductList"
              @selection-change="handleTbProcuredProductSelectionChange"
              ref="tbProcuredProduct"
              height="600px"
              width="100%"
              :span-method="batchSpanMethod"
            >
              <el-table-column
                type="selection"
                width="50"
                align="center"
                min-width="100"
              />
              <el-table-column
                label="序号"
                align="center"
                prop="index"
                min-width="100"
              />
              <el-table-column
                label="图片"
                prop="imgName"
                align="center"
                min-width="100"
              >
                <template slot-scope="scope">
                  <div class="image-container">
                    <image-preview
                      v-for="(image, index) in scope.row.imgName"
                      :key="index"
                      :src="image"
                      :width="50"
                      :height="50"
                      class="image-item"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="SKU" prop="sku" min-width="100" />
              <el-table-column label="GTIN" prop="gtin" min-width="140" />
              <el-table-column
                label="产品名称"
                prop="productName"
                min-width="150"
              >
                <template slot-scope="scope">
                  <el-tooltip
                    v-if="scope.row.productName"
                    :content="scope.row.productName"
                    placement="top"
                    :disabled="scope.row.productName.length <= 10"
                  >
                    <span class="text-ellipsis">
                      {{ scope.row.productName.slice(0, 10) }}
                      <span v-if="scope.row.productName.length > 10">...</span>
                    </span>
                  </el-tooltip>
                  <span v-else>-</span>
                </template>
              </el-table-column>

              <el-table-column
                label="单价"
                prop="productPrice"
                min-width="100"
              />
              <el-table-column label="采购数量" prop="number" min-width="100" />
              <el-table-column
                label="已转数量"
                prop="turnedNumber"
                min-width="100"
              />
              <el-table-column
                label="可转数量"
                prop="transferableNumber"
                min-width="100"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model.number="scope.row.transferableNumber"
                    @input="handleRateChangeRow(scope.row)"
                    placeholder=""
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="合计数量"
                prop="totalQuantity"
                align="center"
                min-width="100"
              >
                <template slot-scope="scope">
                  <!-- 根据当前行的 sku 去计算属性 skuNumberSums 里取值 -->
                  <span>{{ skuTransferableNumberSums[scope.row.sku] }}</span>
                </template>
              </el-table-column>
              <!-- 货币单位列 -->
              <el-table-column
                label="货币单位"
                prop="monetaryId"
                min-width="150"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.monetaryId"
                    disabled
                    placeholder=""
                    @change="handleCurrencyChangeRow(scope.row)"
                  >
                    <el-option
                      v-for="item in monetaryOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>

              <!-- 新增每个产品的汇率输入 -->
              <el-table-column label="汇率" prop="currency" min-width="130">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.currency"
                    disabled
                    placeholder=""
                    @input="handleRateChangeRow(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="金额(¥)" align="center" min-width="150">
                <template slot-scope="scope">
                  <span
                    v-if="
                      skuGroupsBatch[scope.row.sku] &&
                      scope.$index === skuGroupsBatch[scope.row.sku].start
                    "
                  >
                    {{ skuAggregatesBatch[scope.row.sku].amountSum.toFixed(2) }}
                  </span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column
                label="税率(%)"
                prop="rate"
                align="center"
                min-width="100"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.rate" disabled placeholder="" />
                </template>
              </el-table-column>
              <el-table-column label="税额(¥)" align="center" min-width="150">
                <template slot-scope="scope">
                  <span
                    v-if="
                      skuGroupsBatch[scope.row.sku] &&
                      scope.$index === skuGroupsBatch[scope.row.sku].start
                    "
                  >
                    {{ skuAggregatesBatch[scope.row.sku].taxSum.toFixed(2) }}
                  </span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column
                label="含税金额(¥)"
                align="center"
                min-width="150"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      skuGroupsBatch[scope.row.sku] &&
                      scope.$index === skuGroupsBatch[scope.row.sku].start
                    "
                  >
                    {{
                      skuAggregatesBatch[scope.row.sku].taxIncludedSum.toFixed(
                        2
                      )
                    }}
                  </span>
                  <span v-else>-</span>
                </template>
              </el-table-column>

              <!-- 新增每个产品的运费输入 -->
              <el-table-column label="运费" prop="freight" min-width="130">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.freight"
                    disabled
                    placeholder=""
                    @change="handleFreightBlur(scope.row)"
                  />
                </template>
              </el-table-column>
              <!-- 新增每个产品的供应商付勾选 -->
              <el-table-column label="供应商付" prop="flag" min-width="100">
                <template slot-scope="scope">
                  <el-checkbox
                    v-model="scope.row.flag"
                    disabled
                    @change="onSupplierPaysChangeRow(scope.row)"
                    >供应商付</el-checkbox
                  >
                </template>
              </el-table-column>
              <!-- 新增总成本列：含税金额+运费 -->
              <el-table-column label="总成本(¥)" align="center" min-width="150">
                <template slot-scope="scope">
                  <span
                    v-if="
                      skuGroupsBatch[scope.row.sku] &&
                      scope.$index === skuGroupsBatch[scope.row.sku].start
                    "
                  >
                    {{
                      skuAggregatesBatch[scope.row.sku].totalCostSum.toFixed(2)
                    }}
                  </span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column label="供应商" prop="vendorId" min-width="270">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.orderNo1688"
                    disabled
                    placeholder=""
                    clearable
                    style="margin-bottom: 8px"
                  />
                  <el-select
                    v-model="scope.row.vendorId"
                    disabled
                    placeholder=""
                    filterable
                    size="medium"
                    @change="handleVendorChangeRow(scope.row)"
                    style="min-width: 250px"
                  >
                    <el-option
                      v-for="item in vendorOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                label="交付时间"
                prop="deliveryTime"
                min-width="230"
              >
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.deliveryTime"
                    disabled
                    type="datetime"
                    placeholder=""
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column
                label="备注"
                prop="productRemark"
                min-width="200"
              >
                <template slot-scope="scope">
                  <el-input
                    type="textarea"
                    v-model="scope.row.productRemark"
                    size="small"
                    placeholder="请输入备注"
                    clearable
                  />
                </template>
              </el-table-column>
            </el-table>
            <!-- 添加一个总成本显示区域 -->
            <div style="margin-top: 20px; text-align: right; font-size: 16px">
              <strong>总成本(¥): </strong>
              <span>{{ totalCost.toFixed(2) }}</span>
            </div>
          </el-tab-pane>
          <el-tab-pane label="合同备注" name="second">
            <el-row>
              <el-col :span="24">
                <editor
                  v-model="form.contract"
                  :min-height="192"
                  ref="quillEditor"
                  :read-only="true"
                />
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormBatch">确 定</el-button>
        <el-button @click="cancelBatch">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 采购产品 -->
    <el-dialog
      :title="titleProcuredProduct"
      :visible.sync="openProcuredProduct"
      width="75%"
      append-to-body
      @close="loadingProcuredProductClose"
      :close-on-click-modal="false"
    >
      <div
        class="app-container"
        style="
          padding: 0px 0px;
          margin-top: -16px;
          color: #606266;
          font-size: 14px;
          word-break: break-all;
        "
      >
        <el-form
          :model="ProcuredProductQueryParams"
          ref="queryFormProcuredProduct"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="SKU" prop="sku">
            <el-input
              v-model="ProcuredProductQueryParams.sku"
              placeholder="请输入产品SKU"
              clearable
              @keyup.enter.native="handleQueryProcuredProduct"
            />
          </el-form-item>
          <el-form-item label="产品名称" prop="productName">
            <el-input
              v-model="ProcuredProductQueryParams.productName"
              placeholder="请输入产品名称"
              clearable
              @keyup.enter.native="handleQueryProcuredProduct"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQueryProcuredProduct"
              >搜索</el-button
            >
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetQueryProcuredProduct"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-table
          v-loading="loadingProcuredProduct"
          :data="productBatchList"
          @selection-change="handleProcuredSelectionChanges"
          height="600px"
          ref="productTable"
          :row-class-name="getRowClass"
          :row-key="'id'"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            :selectable="isRowSelectable"
            :reserve-selection="true"
          />
          <el-table-column
            label="图片"
            prop="imgName"
            align="center"
            min-width="100"
          >
            <template slot-scope="scope">
              <div class="image-container">
                <image-preview
                  v-for="(image, index) in scope.row.imgName"
                  :key="index"
                  :src="image"
                  :width="50"
                  :height="50"
                  class="image-item"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="SKU" align="center" prop="sku" />
          <el-table-column label="产品名称" align="center" prop="productName">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                :content="scope.row.productName"
                placement="top"
              >
                <span v-if="scope.row.productName">
                  {{ scope.row.productName.slice(0, 10) }}
                  <span v-if="scope.row.productName.length > 10">...</span>
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="GTIN" align="center" prop="gtin" />
          <el-table-column
            label="产品价格"
            align="center"
            prop="productPrice"
          />
          <el-table-column label="数量" align="center" min-width="100">
            <template slot-scope="scope">
              <span>
                {{ scope.row.number }}个
                <span v-if="scope.row.originalPurchaseQuantity">
                  (原：{{ scope.row.originalPurchaseQuantity }}个)
                </span>
              </span>
            </template>
          </el-table-column>

          <el-table-column
            label="已转数量"
            align="center"
            prop="turnedNumber"
          />
          <el-table-column
            label="可转数量"
            align="center"
            prop="transferableNumber"
          >
            <template slot-scope="scope">
              <span
                :class="{ 'zero-quantity': scope.row.transferableNumber <= 0 }"
              >
                {{ scope.row.transferableNumber }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="productRemark">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                :content="scope.row.productRemark"
                placement="top"
              >
                <span v-if="scope.row.productRemark">
                  {{ scope.row.productRemark.slice(0, 10) }}
                  <span v-if="scope.row.productRemark.length > 10">...</span>
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <!-- 操作列中的按钮 -->
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                v-show="!batchProcuredIds.includes(scope.row.id)"
                @click="handleSelectProductToggle(scope.row)"
                size="small"
                :disabled="scope.row.transferableNumber <= 0"
                >选择</el-button
              >
              <el-button
                v-show="batchProcuredIds.includes(scope.row.id)"
                @click="handleSelectProductToggle(scope.row)"
                type="primary"
                size="small"
                :disabled="scope.row.transferableNumber <= 0"
                >已选择</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="totalProcuredProduct > 0"
          :total="totalProcuredProduct"
          :page.sync="ProcuredProductQueryParams.pageNum"
          :limit.sync="ProcuredProductQueryParams.pageSize"
          @pagination="getProductQuery"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading"
          @click="submitFormProcuredProduct"
          >确 定</el-button
        >
        <el-button @click="cancelProcuredProduct">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 撤销下单 -->
    <el-dialog
      :title="titleQuash"
      :visible.sync="openQuash"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-checkbox
        :indeterminate="isIndeterminate"
        v-model="checkAll"
        @change="handleCheckAllChange"
        >全选</el-checkbox
      >
      <div style="margin: 15px 0"></div>
      <el-checkbox-group
        v-model="checkedCities"
        @change="handleCheckedCitiesChange"
      >
        <el-checkbox v-for="city in cities" :label="city" :key="city">{{
          city
        }}</el-checkbox>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormQuash">确 定</el-button>
        <el-button @click="cancelQuash">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 采购计划详情窗口 -->
    <el-dialog
      :title="'查看详情 - ' + detailForm.planNumber"
      :visible.sync="openDetail"
      width="90%"
      append-to-body
    >
      <el-form ref="detailForm" :model="detailForm" label-width="80px">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="基础信息" name="first">
            <el-row>
              <el-col :span="6">
                <el-form-item label="计划单号" prop="planNumber">
                  <el-input
                    v-model="detailForm.planNumber"
                    :disabled="true"
                    placeholder=""
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购日期" prop="planDate">
                  <el-date-picker
                    clearable
                    v-model="detailForm.planDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder=""
                    style="width: 210px"
                    :disabled="true"
                    :default-value="new Date().toISOString().split('T')[0]"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购公司" prop="companyId">
                  <treeselect
                    v-model="detailForm.companyId"
                    :disabled="true"
                    :options="companyOptions"
                    :show-count="true"
                    placeholder=""
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购部门" prop="deptName">
                  <el-input
                    v-model="detailForm.deptName"
                    :disabled="true"
                    placeholder=""
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="采购人员" prop="userName">
                  <el-input
                    v-model="detailForm.userName"
                    :disabled="true"
                    placeholder=""
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="预入仓库" prop="warehouseId">
                  <treeselect
                    v-model="detailForm.warehouseId"
                    :disabled="true"
                    :options="warehouseOptions"
                    :show-count="true"
                    placeholder=""
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="销售计划" prop="salesPlanNumber">
                  <el-input
                    v-model="detailForm.salesPlanNumber"
                    placeholder=""
                    :disabled="true"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 隐藏的输入字段 -->
            <el-input type="hidden" v-model="detailForm.salesPlanId"></el-input>
            <el-row>
              <el-col :span="24">
                <el-form-item label="交货地址" prop="deliveryAddress">
                  <el-input
                    v-model="detailForm.deliveryAddress"
                    :disabled="true"
                    placeholder=""
                    type="textarea"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="planRemark">
                  <el-input
                    v-model="detailForm.planRemark"
                    placeholder=""
                    :disabled="true"
                    type="textarea"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="合同备注" name="second">
            <el-row>
              <el-col :span="24">
                <editor
                  v-model="detailForm.contract"
                  :min-height="192"
                  ref="quillEditor"
                  :read-only="true"
                />
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <el-row
        type="flex"
        justify="center"
        align="middle"
        style="margin: 20px 0"
      >
        <el-col :span="24" style="text-align: center">
          <el-alert
            :title="'采购订单共有 ' + this.orderTotal + ' 笔'"
            type="info"
            :closable="false"
            show-icon
          />
        </el-col>
      </el-row>

      <el-divider content-position="center">订单详情</el-divider>

      <el-form
        :model="ordersQuery"
        ref="ordersQueryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
        style="
          margin: auto;
          display: flex;
          justify-content: center;
          align-items: center;
        "
      >
        <el-form-item label="采购单号" prop="ordersNumber">
          <el-input
            v-model="ordersQuery.ordersNumber"
            placeholder="请输入采购单号"
            clearable
            @keyup.enter.native="handleOrderQuery"
          />
        </el-form-item>
        <el-form-item label="付款状态" prop="paymentStatus">
          <el-select
            v-model="ordersQuery.paymentStatus"
            placeholder="请选择付款状态"
            clearable
          >
            <el-option
              v-for="dict in dict.type.payment_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleOrderQuery"
            >搜索</el-button
          >
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="resetOrdersQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loading"
        :data="OrderList"
        @selection-change="handleSelectionChange"
        style="width: 100%; table-layout: fixed"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column align="center" width="20" type="expand">
          <template slot-scope="scope">
            <el-table
              :data="scope.row.ordersProductList"
              ref="procuredOrdersProduct"
              style="width: 100%"
              :row-class-name="rowTbProcuredProductIndex"
            >
              <el-table-column
                label="图片"
                prop="imagePath"
                align="center"
                min-width="200"
                :selectable="
                  (row) => row.returnCompletedStatus !== 1 && row.returnCompletedStatus !== '1'
                "
              >
                <template slot-scope="scope">
                  <div class="image-container">
                    <image-preview
                      v-for="(image, index) in scope.row.imagePath"
                      :key="index"
                      :src="image"
                      :width="50"
                      :height="50"
                      class="image-item"
                    />
                  </div>
                </template>
              </el-table-column>
              <!-- 产品sku -->
              <el-table-column label="SKU" prop="sku" :min-width="120">
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="scope.row.sku || '-'"
                    placement="top"
                  >
                    <span>{{ scope.row.sku || "-" }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column label="GTIN" align="center" min-width="140">
                <template slot-scope="childScope">
                  <div
                    v-if="childScope.row.gtins && childScope.row.gtins.length"
                  >
                    <div
                      v-for="(gtin, index) in childScope.row.gtins"
                      :key="index"
                    >
                      {{ gtin }}
                    </div>
                  </div>
                  <div v-else>-</div>
                </template>
              </el-table-column>
              <!-- 产品名称 -->
              <el-table-column
                label="产品名称"
                prop="productName"
                :min-width="150"
              >
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="scope.row.productName || '-'"
                    placement="top"
                  >
                    <span>{{ scope.row.productName || "-" }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <!-- 产品价格 -->
              <el-table-column
                label="产品价格"
                prop="productPrice"
                :min-width="100"
              >
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="
                      scope.row.productPrice != null
                        ? scope.row.productPrice.toString()
                        : '-'
                    "
                    placement="top"
                  >
                    <span>{{
                      scope.row.productPrice != null
                        ? scope.row.productPrice
                        : "-"
                    }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <!-- 数量 -->
              <el-table-column
                label="数量"
                prop="transferableNumber"
                :min-width="100"
              >
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="
                      scope.row.transferableNumber != null
                        ? scope.row.transferableNumber.toString()
                        : '-'
                    "
                    placement="top"
                  >
                    <span>{{
                      scope.row.transferableNumber != null
                        ? scope.row.transferableNumber
                        : "-"
                    }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column align="center" :min-width="100">
                <template v-slot:header="scope">
                  <span>运费</span>
                </template>
                <!-- 运费数据展示 -->
                <template v-slot="scope">
                  <div>
                    <!-- 判断 freight 是否为 null -->
                    <span>{{
                      scope.row.freight !== null
                        ? scope.row.freight.toString()
                        : "-"
                    }}</span>
                    <div style="margin-top: 5px">
                      <!-- 如果 flag 不为 null，则根据 flag 值判断显示哪种标签 -->
                      <template v-if="scope.row.flag !== null">
                        <el-tooltip
                          content="供应商付运费"
                          placement="top"
                          v-if="scope.row.flag == 1"
                        >
                          <el-tag type="success" size="mini">供应商付</el-tag>
                        </el-tooltip>
                        <el-tooltip content="自己付运费" placement="top" v-else>
                          <el-tag type="info" size="mini">自付</el-tag>
                        </el-tooltip>
                      </template>
                      <!-- 如果 flag 为 null，则显示默认占位符 -->
                      <template v-else>
                        <span>-</span>
                      </template>
                    </div>
                  </div>
                </template>
              </el-table-column>

              <!-- 税率 -->
              <el-table-column label="税率" prop="productRate" :min-width="100">
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="
                      scope.row.productRate != null
                        ? scope.row.productRate.toString() + '%'
                        : '-'
                    "
                    placement="top"
                  >
                    <span>{{
                      scope.row.productRate != null
                        ? scope.row.productRate + "%"
                        : "-"
                    }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <!-- 金额 -->
              <el-table-column label="金额" prop="amount" :min-width="100">
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="
                      scope.row.amount != null
                        ? scope.row.amount.toString()
                        : '-'
                    "
                    placement="top"
                  >
                    <span>{{
                      scope.row.amount != null ? scope.row.amount : "-"
                    }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <!-- 总成本 -->
              <el-table-column label="总成本" prop="totalCost" :min-width="120">
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="
                      scope.row.totalCost != null
                        ? scope.row.totalCost.toString()
                        : '-'
                    "
                    placement="top"
                  >
                    <span>{{
                      scope.row.totalCost != null ? scope.row.totalCost : "-"
                    }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <!-- 单品成本 -->
              <el-table-column label="单品成本" :min-width="120">
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="
                      scope.row.transferableNumber &&
                      scope.row.totalCost != null
                        ? (
                            scope.row.totalCost / scope.row.transferableNumber
                          ).toFixed(2)
                        : '-'
                    "
                    placement="top"
                  >
                    <span>
                      {{
                        scope.row.transferableNumber &&
                        scope.row.totalCost != null
                          ? (
                              scope.row.totalCost / scope.row.transferableNumber
                            ).toFixed(2)
                          : "-"
                      }}
                    </span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <!-- 入库数量 -->
              <el-table-column
                label="入库数量"
                prop="storageNumber"
                :min-width="120"
              >
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="
                      scope.row.storageNumber != null
                        ? scope.row.storageNumber.toString()
                        : '-'
                    "
                    placement="top"
                  >
                    <span>{{
                      scope.row.storageNumber != null
                        ? scope.row.storageNumber
                        : "-"
                    }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <el-table-column label="供应商" prop="vendorId" min-width="270">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.vendorId"
                    disabled
                    placeholder=""
                    filterable
                    size="medium"
                    style="min-width: 250px"
                  >
                    <el-option
                      v-for="item in vendorOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column
                label="交付时间"
                prop="deliveryTime"
                min-width="230"
              >
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.deliveryTime"
                    disabled
                    type="datetime"
                    placeholder=""
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>

              <!-- 货币单位列 -->
              <el-table-column
                label="货币单位"
                prop="monetaryId"
                min-width="150"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.monetaryId"
                    placeholder=""
                    disabled
                    @change="handleCurrencyChangeRow(scope.row)"
                  >
                    <el-option
                      v-for="item in monetaryOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>

              <!-- 新增每个产品的汇率输入 -->
              <el-table-column label="汇率" prop="currency" min-width="130">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.currency"
                    disabled
                    placeholder=""
                    @input="handleRateChangeRow(scope.row)"
                  />
                </template>
              </el-table-column>
              <!-- 备注 -->
              <el-table-column
                label="备注"
                prop="productRemark"
                :min-width="120"
              >
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="scope.row.productRemark || '无'"
                    placement="top"
                  >
                    <span>{{ scope.row.productRemark || "无" }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <el-table-column label="采购单号" align="center" prop="ordersNumber" />
        <el-table-column label="寄往仓库" align="center" width="200">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              :content="detailForm.companyName"
              placement="top"
            >
              <span v-if="detailForm.companyName">
                {{ detailForm.companyName.slice(0, 10) }}
                <span v-if="detailForm.companyName.length > 10">...</span>
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- 新增批次号列 -->
        <el-table-column
          label="批次号"
          align="center"
          prop="purchaseBatchNumber"
        >
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              :content="scope.row.purchaseBatchNumber || '-'"
              placement="top"
            >
              <span>{{ scope.row.purchaseBatchNumber || "-" }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="下单人" align="center">
          <template slot-scope="scope">
            {{ scope.row.approver }}<br />{{
              parseTime(scope.row.approvedTime, "{y}-{m}-{d}")
            }}
          </template>
        </el-table-column>
        <el-table-column label="总件数" align="center" prop="total" />
        <el-table-column label="采购员" align="center">
          <template slot-scope="scope">
            <span>{{ detailForm.userName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="运费" align="center" prop="freight" />
        <el-table-column label="应付金额" align="center" prop="amountDue" />
        <el-table-column label="入库状态" align="center" prop="inboundStatus">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.inbound_status"
              :value="scope.row.inboundStatus"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="入库总数量"
          align="center"
          prop="inboundNumber"
        />
      </el-table>

      <pagination
        v-show="orderTotal > 0"
        :total="orderTotal"
        :page.sync="ordersQuery.pageNum"
        :limit.sync="ordersQuery.pageSize"
        @pagination="handleOrderQuery"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="openDetail = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 审核申请 -->
    <el-dialog
      :title="audit"
      :visible.sync="openAudit"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
    >
      <div>
        <el-tabs
          type="border-card"
          class="auditStyle"
          @tab-click="handleTabClick"
          v-model="activeTab"
        >
          <el-tab-pane name="toAudit">
            <span slot="label"><i class="el-icon-date"></i>待我审核</span>
            <div class="head-container">
              <el-input
                v-model="nickName"
                placeholder="请输入申请人"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
                @input="
                  () => {
                    pageParams.audited.pageNum = 1;
                    loadData();
                  }
                "
              />
            </div>
            <div class="show-frame-container">
              <template
                v-if="tabData[activeTab] && tabData[activeTab].length > 0"
              >
                <div
                  class="show-frame"
                  v-for="(item, index) in tabData[activeTab]"
                  :key="index"
                  @click="borderTrigger(item)"
                >
                  <image-preview :src="item.avatar" :width="50" :height="50" />

                  <div class="plan-size">
                    <h4>{{ item.userName }}提交的采购计划</h4>
                  </div>
                  <div class="singleHanded-css">
                    申请信息：{{ item.userName }}/{{ item.createTime }}
                  </div>

                  <div class="planNumber-css">
                    采购计划号：{{ item.planNumber }}
                  </div>

                  <div class="mannerName-css">
                    预入仓库：{{ item.warehouseName }}
                  </div>
                  <div class="shipAmoutMy-css">
                    实际金额：<strong>{{
                      item.actualAmount !== null &&
                      item.actualAmount !== undefined
                        ? item.actualAmount
                        : "-"
                    }}</strong>
                  </div>
                  <div class="planStatusMy-css">
                    <dict-tag
                      :options="dict.type.tb_procured_plan"
                      :value="item.planStatus"
                    />
                    <el-button
                      type="text"
                      style="margin-left: 15px"
                      @click.stop="planProcessLog(item)"
                      >日志记录</el-button
                    >
                  </div>
                </div>
              </template>
              <div v-else class="no-data">暂无数据。</div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="我已审核" name="audited">
            <el-input
              v-model="nickNameReviewed"
              placeholder="请输入申请人"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
              @input="
                () => {
                  pageParams.audited.pageNum = 1;
                  loadData();
                }
              "
            />
            <div class="show-frame-container">
              <template v-if="tabData[activeTab].length > 0">
                <div
                  class="show-frame"
                  v-for="(item, index) in tabData[activeTab]"
                  :key="index"
                >
                  <image-preview :src="item.avatar" :width="50" :height="50" />

                  <div class="plan-size">
                    <h4>{{ item.userName }}提交的销售计划</h4>
                  </div>
                  <div class="singleHanded-css">
                    申请信息：{{ item.userName }}/{{ item.createTime }}
                  </div>

                  <div class="planNumber-css">
                    采购计划号：{{ item.planNumber }}
                  </div>
                  <div class="mannerName-css">
                    预入仓库：{{ item.warehouseName }}
                  </div>
                  <div class="planProcessTime-css">
                    审核时间：{{
                      parseTime(item.processTime, "{y}-{m}-{d}-{h}:{m}:{s}")
                    }}
                  </div>
                  <div class="planProcessStatus-css">
                    <dict-tag
                      :options="dict.type.process_status"
                      :value="item.processStatus"
                    />
                    <el-button
                      type="text"
                      style="margin-left: 15px"
                      @click="planProcessLog(item)"
                      >日志记录</el-button
                    >
                  </div>

                  <div class="shipTimeReady-css" style="">
                    实际金额：<strong>{{ item.actualAmount }}</strong>
                  </div>
                  <div class="planStatus-css">
                    <dict-tag
                      :options="dict.type.tb_procured_plan"
                      :value="item.planStatus"
                    />
                  </div>
                </div>
              </template>
              <div v-else class="no-data">暂无数据。</div>
            </div>
          </el-tab-pane>
          <el-tab-pane name="myAudit" label="我发起的">
            <div class="show-frame-container">
              <template v-if="tabData[activeTab].length > 0">
                <div
                  class="show-frame"
                  v-for="(item, index) in tabData[activeTab]"
                  :key="index"
                >
                  <image-preview :src="item.avatar" :width="50" :height="50" />

                  <div class="plan-size">
                    <h4>{{ item.userName }}提交的采购计划</h4>
                  </div>
                  <div class="singleHanded-css">
                    申请信息：{{ item.userName }}//{{ item.createTime }}
                  </div>

                  <div class="planNumber-css">
                    采购订单号：{{ item.planNumber }}
                  </div>
                  <div class="mannerName-css">
                    预入仓库：{{ item.warehouseName }}
                  </div>
                  <div class="shipAmoutMy-css">
                    实际金额：<strong>{{ item.actualAmount }}</strong>
                  </div>
                  <div class="planStatusMy-css">
                    <dict-tag
                      :options="dict.type.tb_procured_plan"
                      :value="item.planStatus"
                    />
                    <el-button
                      type="text"
                      style="margin-left: 15px"
                      @click.stop="planProcessLog(item)"
                      >日志记录</el-button
                    >
                  </div>
                </div>
              </template>
              <div v-else class="no-data">暂无数据。</div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <pagination
        v-show="tabTotals[activeTab] > 0"
        :total="tabTotals[activeTab]"
        :page.sync="pageParams[activeTab].pageNum"
        :limit.sync="pageParams[activeTab].pageSize"
        @pagination="handlePagination"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelTreat">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核详情 -->
    <el-drawer title="详情" :visible.sync="drawer">
      <div class="drawerValueUserImg">
        <image-preview
          :src="this.drawerValue.avatar"
          :width="50"
          :height="50"
        />
      </div>
      <div class="drawerValueSingleHanded">
        <h3>{{ this.drawerValue.userName }}提交的采购计划</h3>
      </div>
      <div class="drawerValuePlanStatus">
        <dict-tag
          :options="dict.type.tb_procured_plan"
          :value="this.drawerValue.planStatus"
        />
      </div>
      <el-descriptions class="margin-top" :column="1" direction="vertical">
        <el-descriptions-item label="计划编号"
          ><span style="color: black">{{
            this.drawerValue.planNumber
          }}</span></el-descriptions-item
        >
        <el-descriptions-item label="申请人"
          ><span style="color: black">{{
            this.drawerValue.userName
          }}</span></el-descriptions-item
        >
        <el-descriptions-item label="部门">
          <span style="color: black">{{
            this.drawerValue.deptName
          }}</span></el-descriptions-item
        >
        <el-descriptions-item label="预入仓库">
          <span style="color: black">
            {{ this.drawerValue.warehouseName }}
          </span>
        </el-descriptions-item>
      </el-descriptions>
      <hr />
      <div>
        <div>
          <image-preview
            :src="this.drawerValue.avatar"
            :width="50"
            :height="50"
          />
          <div class="sponsor">发起人</div>
          <div class="sponsor-name">{{ this.drawerValue.userName }}</div>
          <div class="sponsor-time">
            {{ parseTime(this.drawerValue.createTime, "{y}-{m}-{d}") }}
            {{ parseTime(this.drawerValue.createTime, "{h}:{i}") }}
          </div>
        </div>
        <div class="_scroll-container">
          <div
            v-for="(item, index) in planProcessData"
            :key="index"
            :class="index === 0 ? '' : 'postUserDept-css'"
          >
            <image-preview :src="item.avatar" :width="50" :height="50" />
            <div class="sponsor">审批人</div>
            <div class="sponsor-name">
              {{ item.nickName }}
              <span
                v-if="item"
                v-show="item.processStatus == 0 || item.processStatus == null"
              >
                (审核中)
              </span>
              <span v-if="item" v-show="item.processStatus == 1">
                (同意)&nbsp;&nbsp;{{ item.processTime }}
              </span>
              <span v-if="item" v-show="item.processStatus == 2"> (拒绝) </span>
            </div>
            <div class="sponsor-time">
              {{ item.deptName }}
            </div>
            <div class="postUserDept-postName">
              {{ item.roleName }}
            </div>
          </div>
        </div>
      </div>
      <div class="approval">
        <el-input
          v-model="processRemark"
          type="textarea"
          class="processRemark-input"
          placeholder="备注填写"
          rows="3"
        ></el-input>
        <div class="button-group">
          <el-button @click="rejectPlan(drawerValue.planId, 4)" type="danger"
            >拒 绝</el-button
          >
          <el-button type="primary" @click="approvePlan(drawerValue.planId, 1)"
            >同 意</el-button
          >
        </div>
      </div>
    </el-drawer>

    <!-- 审核日志记录 -->
    <el-dialog
      :visible.sync="openLog"
      width="1400px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-table v-loading="loading" :data="PlanProcessLogList" height="500px">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="采购计划号"
          align="center"
          prop="planNumber"
          width="145"
        />
        <el-table-column
          label="审核状态"
          align="center"
          prop="logStatus"
          width="135"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.process_status"
              :value="scope.row.logStatus"
            />
          </template>
        </el-table-column>
        <el-table-column label="审核人" align="center" prop="logApplicant" />
        <el-table-column label="审核时间" align="center" prop="logTime">
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.logTime, "{y}-{m}-{d} {h}:{m}:{s}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核备注" align="center" prop="logRemark" />
        <el-table-column label="制单人" align="center" prop="userName" />
        <el-table-column label="制单日期" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{m}:{s}")
            }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="logTotals > 0"
        :total="logTotals"
        :page.sync="logParam.pageNum"
        :limit.sync="logParam.pageSize"
        @pagination="getPlanProcessLogList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelPlanProcessLog">取消</el-button>
      </div>
    </el-dialog>

    <!-- 撤回审核 -->
    <el-dialog
      title="撤回审核（取消关联：采购订单/申请付款）"
      :visible.sync="openRevoke"
      v-model="dialogVisible"
      width="400px"
    >
      <el-form :model="revoke">
        <el-form-item label="撤回备注：" label-width="100px">
          <el-input
            type="textarea"
            v-model="revoke.revokeRemark"
            placeholder="请输入撤回备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeRevoke">取消</el-button>
        <el-button type="primary" @click="confirmWithdraw">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPlan,
  getPlan,
  getOrderDetails,
  delPlan,
  addPlan,
  updatePlan,
  updatePlanStatus,
  getSelectVendorTreeList,
  getSelectCompanyTreeList,
  getSelectDeptById,
  getSelectPreWarehouseTreeList,
  getSelectMonetaryTreeList,
  getProductById,
  getUpdateProcuredPlanStatus,
  getSelectTbProcuredProductList,
  getSelectTbProcuredProductListById,
  getUpdateProcuredProductSelectedStatus,
  getInsertProcuredOrders,
  getSelectProcuredOrdersPlanId,
  getDeleteProcuredOrdersByOrdersNumber,
  getUpdateProcuredPlanOrdersNumber,
  getPlanWaitProcessList, //待我审核
  getPlanProcessList, //审核流程数据
  updatePlanProcessStatus, //审核
  getPlanReadyProcessList, //我已审核
  selectPlanProcessLogList, //审核日志
  getPlanMyProcessList, //我发起的审核
  getPlanProducts, // 查看采购计划的采购商品
} from "@/api/procured/plan";
import { revokeProcuredPlan } from "@/api/finance/paymentVoucher";
import { getVendor } from "@/api/commodity/vendor";
import { selectByPlanId } from "@/api/commodity/products";
import { getListPlan } from "@/api/sale/plan";
import { formatPath } from "@/api/utils/pathUtils";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import store from "@/store";
export default {
  name: "ProcuredPlan",
  dicts: [
    "tb_procured_plan",
    "sys_job_status",
    "tb_plan",
    "inbound_status",
    "payment_status",
    "process_status", //日志审核状态
  ],
  components: { Treeselect },
  data() {
    return {
      //采购计划详情页面相关数据
      ordersQuery: {
        pageNum: 1,
        pageSize: 10,
      },
      OrderList: [],
      openDetail: false, // 控制采购计划详情窗口显示
      detailForm: {}, // 存储采购计划详情表单的数据
      currencyDisabled: false, // 汇率输入框是否禁用
      // 遮罩层
      loading: false,
      loadingProduct: false,
      loadingProcuredProduct: true,
      // 选中数组
      items: [],
      ids: [],
      idss: [],
      procuredIds: [],
      planStatus: [],
      isSelectingRows: false,
      // 子表选中数据
      checkedTbProcuredProduct: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      orderTotal: 0, //采购计划详情订单总记录数
      /* 采购计划处用到的数据 **/
      // 采购计划表格数据
      planList: [],
      selectedProducts: [],
      selectedProductIds: [], // 已选择的产品ID数组
      selectedShipmentIds: [], // 已选择的销售计划产品明细id
      productsList: [], // 销售计划中的产品列表
      tbProcuredProductList: [], // 回显界面的产品列表
      tempSelectedProductIds: [], // 临时的已选产品ID列表
      tempSelectedShipmentIds: [], // 临时的已选的销售计划产品id
      tempTbProcuredProductList: [], // 临时的已选产品列表

      /* 采购计划分批下单时用到的数据 **/
      productBatchList: [], // 用于当前模块的产品列表
      tempBatchSelectedProducts: [], // 用于当前模块的临时选择产品
      batchSelectedProducts: [], // 用于当前模块的已确认选择产品
      batchProcuredIds: [], // 用于当前模块的勾选的产品ID
      batchOrderProductList: [], //
      // 弹出层标题
      title: "",
      titleSalesPlan: "",
      titleName: "",
      productOpen: false,
      // 是否显示弹出层
      open: false,
      openSalesPlan: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planNumber: null,
        planDate: null,
        planStatus: null,
      },
      // 表单参数
      form: {},
      // 供应商
      vendorOptions: [],
      // 机构管理里
      companyOptions: [],
      // 仓库列表
      warehouseOptions: [],
      //货币单位
      monetaryOptions: [],
      // 表单校验
      // rules: {
      //   planNumber: [
      //     { required: true, message: "采购单号不能为空", trigger: "blur" },
      //   ],
      // },
      activeName: "first",
      selectedProductsMap: {}, // 全局存储跨页选中的产品
      // 产品查询参数
      queryParamProduct: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        salesPlanId: null,
        shipmentsIds: [],
        shipmentsProductIds: null,
      },
      queryParamShipments: {
        pageNum: 1,
        pageSize: 10,
        shipmentsIds: null,
      },
      totalProduct: 0,
      //分批下单名称
      titleBatch: null,
      openBatch: false,
      //采购产品
      titleProcuredProduct: null,
      openProcuredProduct: false,
      ProcuredProductQueryParams: {
        pageNum: 1,
        pageSize: 10,
        sku: null,
        productName: null,
        planId: null,
      },
      // 采购产品表格数据
      productList: [],
      totalProcuredProduct: 0,
      procuredFlag: true,
      //撤销下单名称
      titleQuash: null,
      openQuash: false,
      //撤销下单编号
      checkAll: false,
      checkedCities: [],
      cities: [],
      isIndeterminate: false,
      cityOptions: [],
      procuredProductLength: null,
      //销售计划参数
      queryParamPlan: {
        pageNum: 1,
        pageSize: 10,
        planName: null,
        selectStatus: 0,
        planStatus: 1,
      },
      totalPlan: 0,
      // 销售中心表格数据
      planListIndex: [],
      // 区分新增和编辑的标识
      isEdit: false,
      selection: [],

      //--------审核模板开始-----------
      //当前用户id
      userId: store.getters.userId,
      //存储审核中的数据
      auditData: [],
      auditLength: null,
      nickName: null,
      nickNameReviewed: null,
      //获得已审批的数据
      planReviewed: [],
      //获得已审批的数据条数
      planReviewedLenght: null,
      //获得我发起的审批数据
      planInitiated: [],
      //获得我发起的审批数据条数
      planInitiatedLenght: null,
      //审核提示
      audit: "",
      //审核弹出框
      openAudit: false,
      activeTab: "toAudit",
      pageParams: {
        toAudit: { pageNum: 1, pageSize: 10 },
        audited: { pageNum: 1, pageSize: 10 },
        myAudit: { pageNum: 1, pageSize: 10 },
      },
      tabData: {
        toAudit: [], //待我审核
        audited: [], //我已审核
        myAudit: [], //我的发起
      },

      tabTotals: {
        toAudit: 0,
        audited: 0,
        myAudit: 0,
      },
      planProcessData: [], //审核流程
      isSubmitting: false,
      processRemark: "", //审核拒绝备注
      openLog: false, //审核日志
      PlanProcessLogList: [],
      // 查询参数
      logParam: {
        pageNum: 1,
        pageSize: 10,
      },
      logTotals: 0,

      drawer: false,
      drawerValue: {},
      approvalProcess: {},
      //--------审核模板结束-----------

      //撤回模块
      openRevoke: false,
      dialogVisible: false,
      revoke: { revokeRemark: "" },
      checkPlanId: "",
      checkUserName: "",
      viewMode: false, // 标记是否为查看模式
    };
  },

  created() {
    this.getList();
    this.getVendor();
    this.getCompany();
    this.getSelectDeptById();
    this.getPreWarehouse();
    this.getMonetary();
  },
  computed: {
    // ----------添加采购计划窗口相关计算属性-----------
    procuredPlanTotalCost() {
      return Object.values(this.skuAggregates).reduce(
        (sum, { totalCostSum }) => sum + totalCostSum,
        0
      );
    },
    skuNumberSums() {
      const sums = {};
      // 遍历表格列表数据，根据 sku 进行数量累加
      this.tbProcuredProductList.forEach((item) => {
        const { sku, number } = item;
        if (!sums[sku]) {
          sums[sku] = 0;
        }
        // number 可能是字符串，这里转成数字再相加
        sums[sku] += Number(number) || 0;
      });
      return sums;
    },

    // 根据 SKU 对数据进行统计（需保证数据已经按照需要合并的字段排序）
    skuGroups() {
      const groups = {};
      if (this.tbProcuredProductList && this.tbProcuredProductList.length > 0) {
        this.tbProcuredProductList.forEach((item, index) => {
          const sku = item.sku;
          if (sku) {
            if (!groups[sku]) {
              groups[sku] = { count: 1, start: index };
            } else {
              groups[sku].count += 1;
            }
          }
        });
      }
      return groups;
    },

    skuAggregates() {
      const result = {};
      // 遍历每个 SKU 分组，skuGroups 的结构为 { sku: { start, count } }
      Object.entries(this.skuGroups).forEach(([sku, { start, count }]) => {
        // 计算该组的总数量：取组内每行的 amount 字段累加
        let aggregateQuantity = 0;
        for (let idx = start; idx < start + count; idx++) {
          aggregateQuantity +=
            Number(this.tbProcuredProductList[idx].number) || 0;
        }
        console.log("遍历的start", JSON.stringify(start, null, 2));
        console.log("遍历的count", JSON.stringify(count, null, 2));

        // 拿第一行的数据（也就是合并展示的那一行）的同步值
        const primary = this.tbProcuredProductList[start];

        // 产品单价，用同步之后的 productPrice 来计算
        const unitPrice = Number(primary.productPrice) || 0;
        console.log("计算属性中的单价", JSON.stringify(unitPrice, null, 2));
        // 汇率
        const exchangeRate = Number(primary.currency) || 1;
        console.log("计算属性中的汇率", JSON.stringify(exchangeRate, null, 2));
        // 计算单个的金额：这里假设产品价格为未换算的原币价，则金额 = 单价 * 汇率 * 数量
        const aggregatedAmount = unitPrice * aggregateQuantity * exchangeRate;
        console.log(
          "计算属性中的金额",
          JSON.stringify(aggregatedAmount, null, 2)
        );

        console.log("计算属性中的税率", JSON.stringify(primary.rate, null, 2));

        // 税额重新计算为：金额 × 税率
        const aggregatedTax = (aggregatedAmount * primary.rate) / 100 || 0;
        console.log("计算属性中的税额", JSON.stringify(aggregatedTax, null, 2));
        // 含税金额
        const aggregatedTaxIncluded = aggregatedAmount + aggregatedTax || 0;
        console.log(
          "计算属性中的含税金额",
          JSON.stringify(aggregatedTaxIncluded, null, 2)
        );
        // 运费：遍历该 SKU 分组内所有行，累加每行的 freight
        let aggregatedFreight = 0;
        for (let idx = start; idx < start + count; idx++) {
          aggregatedFreight +=
            Number(this.tbProcuredProductList[idx].freight) || 0;
        }
        console.log(
          "计算属性中的运费",
          JSON.stringify(aggregatedFreight, null, 2)
        );
        // 总成本：含税金额 + 运费（这里运费按照分组内所有行来累加）
        const aggregatedTotalCost = aggregatedTaxIncluded + aggregatedFreight;
        console.log(
          "计算属性中的总成本",
          JSON.stringify(aggregatedTotalCost, null, 2)
        );
        result[sku] = {
          // 重新计算的汇总金额数据
          amountSum: aggregatedAmount,
          taxSum: aggregatedTax,
          taxIncludedSum: aggregatedTaxIncluded,
          totalCostSum: aggregatedTotalCost,
          // 同时也返回汇总数量（便于其他展示或检查）
          quantity: aggregateQuantity,
        };
      });
      return result;
    },
    // ----------分批下单窗口相关计算属性-----------
    totalCost() {
      return Object.values(this.skuAggregatesBatch).reduce(
        (sum, { totalCostSum }) => sum + totalCostSum,
        0
      );
    },
    skuTransferableNumberSums() {
      const sums = {};
      // 遍历表格列表数据，根据 sku 进行数量累加
      this.batchOrderProductList.forEach((item) => {
        const { sku, transferableNumber } = item;
        if (!sums[sku]) {
          sums[sku] = 0;
        }
        // number 可能是字符串，这里转成数字再相加
        sums[sku] += Number(transferableNumber) || 0;
      });
      return sums;
    },
    // 根据 batchOrderProductList 按 SKU 分组
    skuGroupsBatch() {
      const groups = {};
      if (this.batchOrderProductList && this.batchOrderProductList.length > 0) {
        this.batchOrderProductList.forEach((item, index) => {
          const sku = item.sku;
          if (sku) {
            if (!groups[sku]) {
              groups[sku] = { count: 1, start: index };
            } else {
              groups[sku].count += 1;
            }
          }
        });
      }
      return groups;
    },
    // 计算每个 SKU 分组的汇总数据（金额、税额、含税金额、总成本等）
    skuAggregatesBatch() {
      const result = {};
      // 遍历每个 SKU 分组，skuGroupsBatch 的结构为 { sku: { start, count } }
      Object.entries(this.skuGroupsBatch).forEach(([sku, { start, count }]) => {
        // 计算该组的总数量：对组内每行的 number 累加
        let aggregateQuantity = 0;
        for (let idx = start; idx < start + count; idx++) {
          aggregateQuantity +=
            Number(this.batchOrderProductList[idx].transferableNumber) || 0;
        }
        // 取分组内第一行的作为汇总参考
        const primary = this.batchOrderProductList[start];
        // 单价、汇率及金额计算（金额 = 单价 * 汇率 * 数量）
        const unitPrice = Number(primary.productPrice) || 0;
        const exchangeRate = Number(primary.currency) || 1;
        const aggregatedAmount = unitPrice * aggregateQuantity * exchangeRate;
        // 税额：金额 * 税率（/100）
        const aggregatedTax = (aggregatedAmount * primary.rate) / 100 || 0;
        // 含税金额
        const aggregatedTaxIncluded = aggregatedAmount + aggregatedTax;
        // 运费：遍历该 SKU 分组内所有行累加 freight
        let aggregatedFreight = 0;
        for (let idx = start; idx < start + count; idx++) {
          aggregatedFreight +=
            Number(this.batchOrderProductList[idx].freight) || 0;
        }
        // 总成本：含税金额 + 全部分组内行的运费
        const aggregatedTotalCost = aggregatedTaxIncluded + aggregatedFreight;
        result[sku] = {
          amountSum: aggregatedAmount,
          taxSum: aggregatedTax,
          taxIncludedSum: aggregatedTaxIncluded,
          totalCostSum: aggregatedTotalCost,
          quantity: aggregateQuantity,
        };
      });
      return result;
    },
  },
  watch: {
    "form.salesPlanNumber": function (newVal, oldVal) {
      if (newVal != oldVal) {
        this.clearTableData();
      }
    },
  },
  methods: {
    isDisabledByVendor(row) {
      // 在产品列表中查找与当前产品vendorId相同的第一个产品
      const firstProduct = this.tbProcuredProductList.find(
        (item) => item.vendorId === row.vendorId
      );
      // 如果当前行不是首个产品，则返回 true 禁用输入
      return firstProduct && firstProduct !== row;
    },
    handleVendorChangeRow(row) {
      // 遍历列表，更新相同productId的项的vendorId
      this.tbProcuredProductList.forEach((item) => {
        if (item.productId === row.productId) {
          item.vendorId = row.vendorId; // 将当前行的vendorId赋给匹配项
        }
      });
      // 如果当前行因供应商相同被禁用，则将 flag 重置为 false
      if (this.isDisabledByVendor(row)) {
        row.flag = false;
      }
    },

    // 当供应商付状态变化时触发
    onSupplierPaysChangeRow(row) {
      // 先处理当前行：如果勾选，则清空运费
      if (row.flag) {
        row.freight = 0;
      }

      // 查找同一供应商的所有产品
      const sameVendorProducts = this.tbProcuredProductList.filter(
        (item) => item.vendorId == row.vendorId
      );

      // 根据当前行状态同步更新同一供应商的所有产品
      sameVendorProducts.forEach((item) => {
        this.$set(item, "flag", row.flag); // 强制设置为响应式属性
        // 如果为供应商付，则统一将运费置0；否则可根据需求进行其他处理
        if (row.flag) {
          item.freight = 0;
        }
      });
    },
    // getRowKey(row) {
    //   return row.productId;
    // },
    /** 当销售计划发生变更时将对应的产品显示信息进行清空 */
    clearTableData() {
      this.tbProcuredProductList = []; // 清空表格中的数据
    },
    /** 查询采购计划列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then((response) => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.viewMode = false; // 重置为非查看模式
      this.reset();
    },
    handleClose() {
      this.open = false;
      this.viewMode = false;
    },
    // 表单重置
    reset() {
      this.form = {
        planId: null,
        planNumber: null,
        planDate: new Date(),
        vendorId: null,
        companyId: null,
        deptName: this.form.deptName,
        userName: store.getters.nickName,
        warehouseId: null,
        monetaryId: null,
        planStatus: null,
        currency: 1,
        freight: 0,
        templatesId: null,
        discountAmount: 0,
        contract: null,
        planRemark: null,
        deliveryAddress: null,
        deleteStatus: null,
        addTime: null,
        updateTime: null,
        salesPlanNumber: null,
        salesPlanId: null,
        supplierType: null,
      };
      this.tbProcuredProductList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPlanList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.getList();
    },
    resetQueryProduct() {
      this.resetForm("queryFormProduct");
      this.handleQueryProduct();
    },
    /** 产品搜索按钮操作 */
    handleQueryProduct() {
      // this.queryParamProduct.pageNum = 1;
      this.getListProduct();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // 防止 selection 为空导致错误
      if (selection.length > 0) {
        this.checkPlanId = selection[0].planId;
        this.checkUserName = selection[0].userName;
      } else {
        this.checkPlanId = null;
        this.checkUserName = null;
      }

      this.ids = selection.map((item) => item.planId);
      this.planStatus = selection.map((item) => item.planStatus);
      this.items = [...selection];
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.selection = selection;
    },
    // 多选框选中数据
    handleSelectionChanges(selection) {
      if (!this.isSelectingRows) {
        this.tempSelectedProductIds = selection.map((row) => row.productId);
        this.tempSelectedShipmentIds = selection.map((row) => row.shipmentsId);

        // 更新 tempTbProcuredProductList
        this.tempTbProcuredProductList = selection.map((row) => ({
          imgName: row.imgName,
          productName: row.name,
          productPrice: row.price,
          number: row.planSize - row.procuredSelectedCount,
          amount: row.amount,
          sku: row.sku,
          vendorId: row.vendorId,
          productRemark: row.productRemarks,
          deleteStatus: "",
          proNo: row.proNo,
          selectedStatus: 0,
          turnedNumber: 0,
          transferableNumber: 0,
          productId: row.productId,
          shipmentsId: row.shipmentsId,
          gtin: row.gtin,
          flag: false, // 默认不是供应商付
          freight: 0, // 默认为0运费
          currency: 1, // 默认汇率为1
        }));
      }
      this.idss = selection.map((item) => item.shipmentsId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // handleProcuredSelectionChanges(selection) {
    //   this.procuredIds = selection.map((item) => item.id);
    //   this.single = selection.length !== 1;
    //   this.multiple = !selection.length;
    // },

    // 监听勾选变化
    handleProcuredSelectionChanges(selection) {
      this.batchProcuredIds = selection.map((item) => item.id); // 更新选中的ID
      // 3. 遍历当前页所有产品，保持全局映射的同步
      this.productBatchList.forEach((product) => {
        if (this.batchProcuredIds.includes(product.id)) {
          // 如果当前产品被选中，则添加到全局映射中（如果还没有的话）
          this.$set(this.selectedProductsMap, product.id, product);
        } else {
          // 如果当前产品未被选中，则从全局映射中移除
          this.$delete(this.selectedProductsMap, product.id);
        }
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.currency = 1; // 设置汇率为1
      this.currencyDisabled = true; // 禁用汇率输入框
      this.queryParamProduct.shipmentsIds = [];
      this.isEdit = false; // 设置为新增模式
      this.title = "添加采购计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const planId = row.planId || this.ids;
      this.isEdit = true; // 设置为新增模式
      getPlan(planId).then((response) => {
        this.open = true;
        this.title = "修改采购计划";
        this.form = response.data;
        this.queryParamProduct.salesPlanId = response.data.salesPlanId;

        // 在赋值之前，遍历返回的产品列表，更新每个产品的属性
        if (
          response.data.tbProcuredProductList &&
          response.data.tbProcuredProductList.length > 0
        ) {
          response.data.tbProcuredProductList.forEach((product) => {
            // 如果货币单位为 CNY，即 monetaryId 为 1，则禁用该产品行的汇率输入框
            product.currencyDisabled = product.monetaryId == 1;
            // 如果 flag 为 true 则勾选供应商付，否则不勾选
            product.isSupplierPaid = product.flag == true;
          });
        }
        // 确保数据更新是响应式的
        this.$nextTick(() => {
          this.tbProcuredProductList = response.data.tbProcuredProductList;
          this.queryParamProduct.shipmentsIds = [];
          this.tbProcuredProductList.forEach((row, index) => {
            this.queryParamProduct.shipmentsIds.push(row.productId); // 行号从1开始
          });
        });
      });
    },
    /** 导航栏修改按钮操作 */
    SelectedHandleUpdate() {
      // 多选操作：检查选中的所有行的状态
      let allUnlocked = this.items[0].planStatus == 0;

      if (!allUnlocked) {
        this.$message.error(
          "勾选行存在已核准的采购计划，请反核准之后再进行操作！"
        );
        return; // 阻止继续执行
      }
      this.reset();
      const planId = this.ids;
      this.isEdit = true; // 设置为编辑模式
      getPlan(planId).then((response) => {
        this.open = true;
        this.title = "修改采购计划";
        this.form = response.data;
        this.queryParamProduct.salesPlanId = response.data.salesPlanId;
        // 在赋值之前，遍历返回的产品列表，更新每个产品的属性
        if (
          response.data.tbProcuredProductList &&
          response.data.tbProcuredProductList.length > 0
        ) {
          response.data.tbProcuredProductList.forEach((product) => {
            // 如果货币单位为 CNY，即 monetaryId 为 1，则禁用该产品行的汇率输入框
            product.currencyDisabled = product.monetaryId == 1;
            // 如果 flag 为 true 则勾选供应商付，否则不勾选
            product.isSupplierPaid = product.flag == true;
          });
        }
        // 确保数据更新是响应式的
        this.$nextTick(() => {
          this.tbProcuredProductList = response.data.tbProcuredProductList;
          this.queryParamProduct.shipmentsIds = [];
          this.tbProcuredProductList.forEach((row, index) => {
            this.queryParamProduct.shipmentsIds.push(row.productId); // 行号从1开始
          });
        });
      });
    },
    // 校验采购数量：用于分批下单时
    validateProcurementQuantities(products) {
      let exceededProducts = [];
      let invalidProducts = [];
      let emptyTransferableProducts = [];
      let procuredFlag = true; // 初始化标志位

      // 检查每个产品的可转数量是否超出采购数量、为零或未填写
      for (let i = 0; i < products.length; i++) {
        const product = products[i];
        const totalTurnedNumber =
          parseInt(product.turnedNumber || 0) +
          parseInt(product.transferableNumber || 0);

        // 验证 transferableNumber 是否未填写或为 NaN
        if (
          product.transferableNumber === undefined ||
          product.transferableNumber === null ||
          product.transferableNumber === "" ||
          isNaN(parseInt(product.transferableNumber))
        ) {
          emptyTransferableProducts.push(product);
          procuredFlag = false;
          continue; // 跳过后续验证，进入下一个循环
        }

        // 验证已采购数量不能小于等于 0
        if (parseInt(product.transferableNumber) <= 0) {
          invalidProducts.push(product);
          procuredFlag = false;
        }

        // 验证是否超出数量
        if (totalTurnedNumber > parseInt(product.number)) {
          exceededProducts.push(product); // 将超出数量的产品添加到数组中
          procuredFlag = false;
        }
      }

      // 如果存在未填写可转数量的产品，提示警告信息
      if (emptyTransferableProducts.length > 0) {
        let proNoList = emptyTransferableProducts.map((p) => p.sku).join(",");
        this.$modal.msgWarning("产品sku " + proNoList + " 的可转数量未填写！");
      }

      // 如果存在采购数量为 0 或负数的产品，提示警告信息
      if (invalidProducts.length > 0) {
        let proNoList = invalidProducts.map((p) => p.proNo).join(",");
        this.$modal.msgWarning(
          "产品sku " + proNoList + " 的可转数量必须大于 0！"
        );
      }

      // 如果存在超出数量的产品，提示警告信息
      if (exceededProducts.length > 0) {
        let proNoList = exceededProducts.map((p) => p.proNo).join(",");
        this.$modal.msgWarning(
          "产品sku " + proNoList + " 超出可采购数量范围！"
        );
      }

      return procuredFlag;
    },
    // 提取校验逻辑
    validateCommonProductFields(products) {
      // 检查货币单位是否一致
      const uniqueMonetaryIds = new Set(products.map((p) => p.monetaryId));
      if (uniqueMonetaryIds.size > 1) {
        this.$modal.msgError("产品列表中的货币单位不一致，请统一货币单位！");
        return false;
      }
      // 遍历每个产品做必填校验
      for (let i = 0; i < products.length; i++) {
        const product = products[i];
        // 检查采购数量
        if (
          product.number === undefined ||
          product.number === null ||
          product.number === "" ||
          isNaN(parseInt(product.number)) ||
          parseInt(product.number) <= 0
        ) {
          this.$modal.msgError(
            `产品 ${product.sku} 的采购数量必须为大于0的有效数字！`
          );
          return false;
        }
        // 单价必填校验
        if (
          product.productPrice === undefined ||
          product.productPrice === null ||
          product.productPrice === ""
        ) {
          this.$modal.msgError(`产品 ${product.sku} 的单价不能为空！`);
          return false;
        }
        // 税率必填校验
        if (
          product.rate === undefined ||
          product.rate === null ||
          product.rate === ""
        ) {
          this.$modal.msgError(`产品 ${product.sku} 的税率不能为空！`);
          return false;
        }
        // 货币单位必填校验
        if (
          product.monetaryId === undefined ||
          product.monetaryId === null ||
          product.monetaryId === ""
        ) {
          this.$modal.msgError(`产品 ${product.sku} 的货币单位不能为空！`);
          return false;
        }
        // 汇率必填校验
        if (
          product.currency === undefined ||
          product.currency === null ||
          product.currency === ""
        ) {
          this.$modal.msgError(`产品 ${product.sku} 的汇率不能为空！`);
          return false;
        }
        // 当未勾选供应商付时，运费必须填写
        if (
          !product.flag &&
          (product.freight === undefined ||
            product.freight === null ||
            product.freight === "")
        ) {
          this.$modal.msgError(`产品 ${product.sku} 的运费不能为空！`);
          return false;
        }
        // 供应商必填校验
        if (
          product.vendorId === undefined ||
          product.vendorId === null ||
          product.vendorId === ""
        ) {
          this.$modal.msgError(`产品 ${product.sku} 的供应商不能为空！`);
          return false;
        }
        // 交付时间必填校验
        if (
          product.deliveryTime === undefined ||
          product.deliveryTime === null ||
          product.deliveryTime === ""
        ) {
          this.$modal.msgError(`产品 ${product.sku} 的交付时间不能为空！`);
          return false;
        }
      }
      // 校验同一供应商的产品“供应商付”设置是否一致
      const vendorGroups = {};
      products.forEach((product) => {
        const vendor = product.vendorId;
        if (!vendorGroups[vendor]) {
          vendorGroups[vendor] = [];
        }
        vendorGroups[vendor].push(product);
      });
      for (const vendor in vendorGroups) {
        const group = vendorGroups[vendor];
        const hasSupplierPaid = group.some((product) => product.flag === true);
        const hasNotSupplierPaid = group.some((product) => !product.flag);
        if (hasSupplierPaid && hasNotSupplierPaid) {
          this.$modal.msgError(
            `供应商为 ${vendor} 的产品存在供应商付设置不一致，请统一设置！`
          );
          return false;
        }
      }
      return true;
    },
    /** 提交按钮 */
    submitForm() {
      let originalPath = this.$route.path; // 当前路径
      let componentPath = formatPath(originalPath);

      if (!this.form.companyId) {
        this.$message.error("采购公司不能为空");
        return;
      }
      if (!this.form.warehouseId) {
        this.$message.error("预入仓库不能为空");
        return;
      }
      if (!this.form.deliveryAddress) {
        this.$message.error("交货地址不能为空");
        return;
      }

      if (
        !Array.isArray(this.tbProcuredProductList) ||
        this.tbProcuredProductList.length === 0
      ) {
        this.$message.error("请添加产品数据");
        return; // 如果 tbProcuredProductList 为空或不是数组，直接返回
      }

      // 同步同一 SKU 分组中缺失字段数据
      // 定义需要同步的字段
      const fieldsToSync = [
        "productPrice",
        "deliveryTime",
        "vendorId",
        "orderNo1688",
        "flag",
        "rate",
        "currency",
        "monetaryId",
      ];

      // 利用计算属性 skuGroups（根据 sku 分组）进行遍历同步
      Object.keys(this.skuGroups).forEach((sku) => {
        const group = this.skuGroups[sku];
        // 如果该分组内有多行数据
        if (group.count > 1) {
          // 使用该分组中第一行作为主行
          const primaryRow = this.tbProcuredProductList[group.start];
          console.log(JSON.stringify(primaryRow, null, 2));
          // 遍历当前分组内其他行
          for (let i = group.start + 1; i < group.start + group.count; i++) {
            fieldsToSync.forEach((field) => {
              this.$set(
                this.tbProcuredProductList[i],
                field,
                primaryRow[field]
              );
            });
            // 重新计算金额、税额和含税金额
            this.calculateAmount(this.tbProcuredProductList[i]);
          }
        }
      });

      console.log(
        "校验通过之前的sku",
        JSON.stringify(this.tbProcuredProductList, null, 2)
      );
      // 校验每行产品数据信息
      if (!this.validateCommonProductFields(this.tbProcuredProductList)) {
        return false;
      }

      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.tbProcuredProductList = this.tbProcuredProductList;

          this.form.shipmentsProductIds = this.queryParamProduct.shipmentsIds;
          for (
            let index = 0;
            index < this.form.tbProcuredProductList.length;
            index++
          ) {
            this.form.tbProcuredProductList[index].imgName = null;
          }
          if (this.form.planId != null) {
            updatePlan(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            for (
              let index = 0;
              index < this.form.tbProcuredProductList.length;
              index++
            ) {
              this.form.tbProcuredProductList[index].turnedNumber = 0;
              this.form.tbProcuredProductList[index].transferableNumber = 0;
            }
            console.log(JSON.stringify(this.form));

            addPlan(this.form, componentPath).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
          // }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planIds = row.planId || this.ids;
      this.$modal
        .confirm('是否确认删除采购计划编号为"' + planIds + '"的数据项？')
        .then(function () {
          return delPlan(planIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    selectedHandleDelete() {
      // 判断 planStatus 是否不等于 0
      const hasApprovedPlan = this.items.some((row) => row.planStatus != 0);
      if (hasApprovedPlan) {
        this.$message.error(
          "勾选行存在已核准的采购计划，请反核准之后再进行操作！"
        );
        return;
      }

      const planIds = this.items.map((row) => row.planId).join(",");
      const planNumber = this.items.map((row) => row.planNumber).join(",");

      this.$modal
        .confirm("是否确认删除采购计划单号为[" + planNumber + "]的数据项？")
        .then(() => {
          return delPlan(planIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** ${subTable.functionName}序号 */
    rowTbProcuredProductIndex({ row, rowIndex }) {
      const baseIndex = `row-${rowIndex}`;
      if (row.returnCompletedStatus == 1 || row.returnCompletedStatus === "1") {
        console.log("触发了");
        
        return `${baseIndex} disabled-row`;
      }
      return baseIndex;
    },
    /** ${subTable.functionName}添加按钮操作 */
    handleAddTbProcuredProduct() {
      if (this.form.salesPlanNumber != null) {
        this.selectedProductIds = this.tbProcuredProductList.map(
          (item) => item.productId
        );
        this.selectedShipmentIds = this.tbProcuredProductList.map(
          (item) => item.shipmentsId
        );
        // 初始化临时选中产品ID列表
        this.tempSelectedProductIds = [...this.selectedProductIds];
        this.tempSelectedShipmentIds = [...this.selectedShipmentIds];
        this.tempTbProcuredProductList = [...this.tbProcuredProductList];
        this.titleName = "添加产品";
        this.productOpen = true;
        this.getListProduct();
      } else {
        this.$message.warning("请选择销售计划");
      }
    },
    /** ${subTable.functionName}删除按钮操作 */
    handleDeleteTbProcuredProduct() {
      if (this.checkedTbProcuredProduct.length == 0) {
        this.$modal.msgError("请先选择要删除的产品数据");
      } else {
        const checkedTbProcuredProduct = this.checkedTbProcuredProduct;

        // 从 selectedProductIds 数组中移除选中的 productId
        this.selectedShipmentIds = this.selectedShipmentIds.filter(
          (productId) => {
            return !checkedTbProcuredProduct.includes(productId);
          }
        );
        // 更新 tbProcuredProductList，过滤掉选中的产品
        this.tbProcuredProductList = this.tbProcuredProductList.filter(
          (item) => {
            return !checkedTbProcuredProduct.includes(item.shipmentsId);
          }
        );
        // 清空已选择的产品
        this.checkedTbProcuredProduct = [];
      }
    },

    handleDeleteTbProcuredProducts() {
      if (this.checkedTbProcuredProduct.length === 0) {
        this.$modal.msgError("请先选择要删除的产品数据");
      } else {
        const checkedTbProcuredProduct = this.checkedTbProcuredProduct;

        this.batchOrderProductList = this.batchOrderProductList.filter(
          function (item) {
            return checkedTbProcuredProduct.indexOf(item.id) === -1;
          }
        );
        // 清空已选择的产品
        this.checkedTbProcuredProduct = [];
        // 清除表格的选择状态
        this.$refs.tbProcuredProduct.clearSelection();
      }
    },

    /** 复选框选中数据 */
    handleTbProcuredProductSelectionChange(selection) {
      this.checkedTbProcuredProduct = selection.map((item) => item.id);
    },
    handleTbProcuredProductSelectionChanges(selection) {
      this.checkedTbProcuredProduct = selection.map((item) => item.shipmentsId);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "procured/plan/export",
        {
          ...this.queryParams,
        },
        `plan_${new Date().getTime()}.xlsx`
      );
    },
    /** 查询供应商的下拉数据结果 */
    getVendor() {
      getSelectVendorTreeList().then((response) => {
        this.vendorOptions = response.data;
      });
    },
    /** 查询机构管理下拉数据结果 */
    getCompany() {
      getSelectCompanyTreeList().then((response) => {
        this.companyOptions = response.data;
      });
    },
    /** 查询部门名称 */
    getSelectDeptById() {
      getSelectDeptById(store.getters.deptId).then((response) => {
        this.form.deptName = response.data.deptName;
      });
    },

    /** 查询仓库 */
    getPreWarehouse() {
      getSelectPreWarehouseTreeList().then((response) => {
        this.warehouseOptions = response.data;
      });
    },

    /** 货币单位 */
    getMonetary() {
      getSelectMonetaryTreeList().then((response) => {
        this.monetaryOptions = response.data;
      });
    },

    /** 查询产品列表，并设置已选择产品的勾选状态 */
    getListProduct() {
      this.loadingProduct = true;
      this.queryParamProduct.shipmentsProductIds = this.tempSelectedProductIds;
      // this.queryParamProduct.salesPlanId = this.form.salesPlanNumber
      selectByPlanId(this.queryParamProduct, this.isEdit).then((response) => {
        let allProducts = response.rows;
        this.productsList = allProducts;
        this.totalProduct = response.total; // 更新总数
        this.loadingProduct = false;

        // 设置标志以防止handleSelectionChanges运行
        this.isSelectingRows = true;

        this.$nextTick(() => {
          this.productsList.forEach((product) => {
            if (this.tempSelectedShipmentIds.includes(product.shipmentsId)) {
              if (this.$refs.myTable) {
                this.$refs.myTable.toggleRowSelection(product, true);
              }
            }
          });
          // 完成选择后重置标志
          this.isSelectingRows = false;
        });
      });
    },

    // 切换产品的选择状态
    toggleSelectProduct(product) {
      const productId = product.productId;
      const shipmentsId = product.shipmentsId;
      const index = this.tempSelectedProductIds.indexOf(productId);
      const index_ = this.tempSelectedShipmentIds.indexOf(shipmentsId);
      if (index_ === -1) {
        // 选择产品
        this.tempSelectedProductIds.push(productId);
        this.tempSelectedShipmentIds.push(shipmentsId);
        this.tempTbProcuredProductList.push({
          imgName: product.imgName,
          productName: product.name, // 产品名称
          productPrice: product.price, // 产品价格
          number: product.planSize - product.procuredSelectedCount, // 数量
          amount: product.amount, // 总金额
          sku: product.sku, // sku
          vendorId: product.vendorId,
          productRemark: product.productRemarks, // 产品备注
          deleteStatus: "", // 删除状态（空）
          proNo: product.proNo, // 产品编号
          selectedStatus: 0, // 选择状态（默认未选中）
          turnedNumber: 0, // 已转数量（默认0）
          transferableNumber: 0, // 可转数量（默认0）
          productId: productId, // 产品ID
          shipmentsId: product.shipmentsId,
          gtin: product.gtin,
          flag: false, // 默认不是供应商付
          freight: 0, // 默认为0运费
          currency: 1, // 默认汇率为1
        });
        // 选中表格中的行
        this.$refs.myTable.toggleRowSelection(product, true);
      } else {
        // 取消选择产品
        this.tempSelectedProductIds.splice(index, 1);
        this.tempSelectedShipmentIds.splice(index_, 1);
        this.tempTbProcuredProductList = this.tempTbProcuredProductList.filter(
          (item) => item.productId !== productId
        );
        // 取消表格中的行选中
        this.$refs.myTable.toggleRowSelection(product, false);
      }
    },
    async submitFormProduct() {
      this.loading = true;
      await new Promise((resolve) => setTimeout(resolve, 1000));
      // 更新实际的已选产品ID列表
      this.selectedProductIds = [...this.tempSelectedProductIds];
      this.selectedShipmentIds = [...this.tempSelectedShipmentIds];
      console.log(JSON.stringify(this.selectedShipmentIds, null, 2));

      this.tbProcuredProductList = [...this.tempTbProcuredProductList];

      // 处理已选择和未选择产品的逻辑
      this.tbProcuredProductList = this.tbProcuredProductList
        // 先排序
        .sort((a, b) => a.vendorId - b.vendorId)
        // 再过滤
        .filter((item) => this.selectedShipmentIds.includes(item.shipmentsId));

      this.productOpen = false; // 关闭产品选择弹窗
      // 模拟异步操作：等待1秒

      // 清空表格中的勾选状态
      if (this.$refs.myTable) {
        this.$refs.myTable.clearSelection();
      }
      this.loading = false;
      // this.handleCurrencyChange();
    },
    /** 取消产品 */
    cancelProduct() {
      this.productOpen = false;
      // 清空临时选中产品ID列表和产品列表
      this.tempSelectedProductIds = [];
      this.tempSelectedShipmentIds = [];
      this.tempTbProcuredProductList = [];

      if (this.$refs.myTable) {
        this.$refs.myTable.clearSelection();
      }
    },

    // autoFillModelNumber(row) {
    //   this.form.
    //   row.amount = row.number * row.productPrice;
    //   row.taxIncluded = row.amount + row.tax;
    // },
    // 计算金额、税额和含税金额
    // autoFillModel(row) {
    //   const exchangeRate = parseFloat(this.form.currency || 1);  // 汇率默认为1
    //   const productPrice = parseFloat(row.productPrice || 0);
    //   const number = parseFloat(row.number || 0);
    //   const rate = parseFloat(row.rate || 0) / 100;  // 转换税率为小数

    //   // 计算金额
    //   row.amount = productPrice * number * exchangeRate;
    //   // 计算税额 (价格 * 数量 * 汇率 * 税率)
    //   row.tax = productPrice * number * exchangeRate * rate;
    //   // 计算含税金额
    //   row.taxIncluded = row.amount + row.tax;
    // },

    //当汇率发生变化时重新计算商品总金额
    // handleCurrencyChange() {
    //   // 更新所有行的金额和税额
    //   this.tbProcuredProductList.forEach(row => this.autoFillModel(row));
    // },

    // 当货币单位为RMB时，将汇率设为1并禁用汇率输入框
    // handleCurrency(value) {
    //   if (value === 1) {  // 假设 RMB 的值为 'RMB'
    //     this.form.currency = 1;  // 设置汇率为1
    //     this.currencyDisabled = true;  // 禁用汇率输入框
    //   } else {
    //     this.currencyDisabled = false;  // 启用汇率输入框
    //   }
    //   // 每次更改货币单位时都重新计算金额和税额
    //   this.handleCurrencyChange();
    // },

    autoFillModelVendorId(row) {
      if (row != null) {
        getVendor(row).then((response) => {
          this.form.contract = response.data.contract;
        });
        this.form.contract = null;
      }
    },
    /** 核准 */
    handleApproved(row) {
      let canApprove = this.selection.every((item) => item.planStatus === 0);
      if (!canApprove) {
        this.$message.error("只能对未核准的计划进行核准！");
        return;
      }

      // const planIds = row.planId || this.ids;
      // this.$modal
      //   .confirm("您确认所选数据将核准吗？")
      //   .then(function () {
      //     return getUpdateProcuredPlanStatus(planIds, true);
      //   })
      //   .then(() => {
      //     this.getList();
      //     if (planIds.length == 1) {
      //       getPlan(planIds).then((response) => {
      //         this.form = response.data;
      //         this.$modal.msgSuccess(
      //           "计划单号：" + this.form.planNumber + "已经核准！"
      //         );
      //       });
      //     } else {
      //       this.$modal.msgSuccess("计划单号批量已核准！");
      //     }
      //   })
      //   .catch(() => { });
    },
    /** 反核准 */
    handleApp(row) {
      let canApprove = this.selection.every((item) => item.planStatus === 1);
      if (!canApprove) {
        this.$message.error("只能对已核准未下单的计划进行核准！");
        return;
      }
      let planStatus = this.planStatus;
      if (planStatus == 2 || planStatus == 3) {
        this.$modal.msgError("所选行中包含部分下单或已下单的采购计划！");
        return;
      }
      const planIds = row.planId || this.ids;
      this.$modal
        .confirm("您确认所选数据将反核准吗？")
        .then(function () {
          return getUpdateProcuredPlanStatus(planIds, false);
        })
        .then(() => {
          this.getList();
          if (planIds.length == 1) {
            getPlan(planIds).then((response) => {
              this.form = response.data;
              this.$modal.msgSuccess(
                "计划单号：" + this.form.planNumber + "反核准成功！"
              );
            });
          } else {
            this.$modal.msgSuccess("计划单号批量已反核准成功！");
          }
        })
        .catch(() => {});
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleUpdate":
          this.handleUpdate(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        case "handleBatch":
          this.handleBatch(row);
          break;
        case "handleQuash":
          this.handleQuash(row);
          break;
        case "handleDetails":
          this.handleDetails(row);
          break;
        case "handleViewProducts":
          this.handleViewProducts(row);
          break;
        default:
          break;
      }
    },
    /** 分批下单 */
    handleBatch(row) {
      this.reset();
      const planId = row.planId || this.ids;

      getPlan(planId).then((response) => {
        this.form = response.data;
        this.openBatch = true;
        this.titleBatch = "分批下单";
        this.batchOrderProductList = [];
      });
    },
    /** 撤销下单 */
    handleQuash(row) {
      this.titleQuash = "请勾选需要撤销的采购订单";
      this.openQuash = true;
      this.cities = [];
      getSelectProcuredOrdersPlanId(row.planId).then((response) => {
        let dataArray = [];
        for (let index = 0; index < response.data.length; index++) {
          this.cityOptions = response.data[index].ordersNumber;
          dataArray.push(this.cityOptions);
          this.cities = dataArray;
        }
      });
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.cities : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
    },
    /** 撤销下单确定按钮 */
    submitFormQuash() {
      const ordersNumber = this.checkedCities;

      if (ordersNumber != "") {
        // 判断选中的选项数量是否等于全部选项数量
        if (this.checkedCities.length === this.cities.length) {
          getUpdateProcuredPlanOrdersNumber(ordersNumber, true);
        } else {
          getUpdateProcuredPlanOrdersNumber(ordersNumber, false);
        }
        getDeleteProcuredOrdersByOrdersNumber(ordersNumber).then((response) => {
          this.$modal.msgSuccess("撤销下单成功");
          this.openQuash = false;
          this.checkedCities = [];
          this.checkAll = false;
          this.getList();
        });
      }
    },
    /** 撤销下单取消按钮 */
    cancelQuash() {},

    // 查询可选产品
    getProductQuery() {
      this.loadingProcuredProduct = true;
      getSelectTbProcuredProductList(this.ProcuredProductQueryParams).then(
        (response) => {
          this.productBatchList = response.rows;
          this.totalProcuredProduct = response.total;
          this.syncBatchSelectedProducts(); // 同步已选择产品状态
          this.loadingProcuredProduct = false;
        }
      );
    },

    // 同步已选择产品的状态
    syncBatchSelectedProducts() {
      this.$nextTick(() => {
        this.productBatchList.forEach((product) => {
          if (this.isBatchProductSelected(product)) {
            this.$refs.productTable.toggleRowSelection(product, true);
          }
        });
      });
    },

    // 判断是否已选择
    isBatchProductSelected(product) {
      return this.batchOrderProductList.some((p) => p.id == product.id);
    },

    /** 在分批下单时添加采购产品 */
    handleAddList(planId) {
      // 首先检查是否选择了供应商类型
      if (!this.form.supplierType) {
        this.$message.warning("请选择供应商类型");
        return;
      }
      // 将分批下单时的 planId 传入，并把供应商类型加入查询参数中
      this.ProcuredProductQueryParams.planId = planId;
      // 新增一项 supplierType 用于后续查询
      this.ProcuredProductQueryParams.supplierType = this.form.supplierType;

      // 触发获取产品列表的函数
      this.getProductQuery();

      this.openProcuredProduct = true;
      this.titleProcuredProduct = "计划单明细";
    },

    /** 搜索按钮操作 */
    handleQueryProcuredProduct() {
      this.ProcuredProductQueryParams.pageNum = 1;
      this.getProductQuery();
    },
    /** 重置按钮操作 */
    resetQueryProcuredProduct() {
      this.resetForm("queryFormProcuredProduct");
      this.handleQueryProcuredProduct();
    },

    // 切换选择状态
    handleSelectProductToggle(row) {
      const index = this.batchProcuredIds.indexOf(row.id);
      if (index !== -1) {
        this.batchProcuredIds.splice(index, 1); // 从已选择列表中移除
        this.$delete(this.selectedProductsMap, row.id);
        this.$refs.productTable.toggleRowSelection(row, false); // 取消勾选
      } else {
        this.batchProcuredIds.push(row.id); // 添加到已选择列表
        this.$set(this.selectedProductsMap, row.id, row);
        this.$refs.productTable.toggleRowSelection(row, true); // 勾选
      }
    },
    /** 分批产品确定按钮 */
    async submitFormProcuredProduct() {
      // const currentSelectedIds = this.productBatchList
      //   .filter(product => this.batchProcuredIds.includes(product.productId))
      //   .map(product => product.productId);

      // // 过滤batchOrderProductList，只保留仍被选中的产品
      // this.batchOrderProductList = this.batchOrderProductList.filter(product =>
      //   currentSelectedIds.includes(product.productId)
      // );

      // // 遍历当前选中的产品列表，添加那些不在batchOrderProductList中的产品
      // this.productBatchList.forEach(product => {
      //   if (this.batchProcuredIds.includes(product.productId) && !this.batchOrderProductList.some(p => p.productId == product.productId)) {
      //     this.batchOrderProductList.push(product);
      //   }
      // });

      // 当前页面选中的产品ID列表（从当前页数据中获取）
      // 将全局选中映射转换成数组，保留跨页数据
      this.loading = true;
      // 模拟异步操作：等待1秒
      await new Promise((resolve) => setTimeout(resolve, 1000));
      this.batchOrderProductList = Object.values(this.selectedProductsMap);
      this.batchOrderProductList.forEach(this.calculateAmount); // 循环调用计算属性，更新计算每一行的属性值
      // 模拟异步操作后再关闭加载效果
      this.loading = false;
      this.cancelProcuredProduct();
    },
    // 分批选择产品时取消选择
    cancelProcuredProduct() {
      this.batchProcuredIds = []; // 清空临时选择列表
      this.openProcuredProduct = false;
      this.$refs.productTable.clearSelection();
    },
    loadingProcuredProductClose() {
      this.cancelProcuredProduct();
    },
    /** 分批下单取消按钮 */
    cancelBatch() {
      let ids = [];
      this.batchOrderProductList.forEach((row) => {
        ids.push(row.productId);
      });
      if (ids.length > 0) {
        // 清空已选中的产品列表
        this.batchOrderProductList = [];
        this.checkedTbProcuredProduct = [];
        // 清除表格的选择状态
        if (this.$refs.tbProcuredProduct) {
          this.$refs.tbProcuredProduct.clearSelection();
        }
        // 关闭分批下单的对话框
        this.openBatch = false;
      } else {
        // 如果没有产品需要更新，直接关闭对话框
        this.openBatch = false;
      }
    },
    submitFormBatch() {
      // // 如果复选框没有选中，确保 flag 的值为 false
      // if (this.form.flag === null) {
      //   this.form.flag = false;
      // }
      // // 判断供应商付运费的勾选框是否未选中
      // if (!this.form.flag) {
      //   // 弹出确认框
      //   this.$confirm('您确定运费为己方付款吗？', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     // 用户点击确定后，继续执行提交逻辑
      //     this.submitBatchFormLogic();
      //   }).catch(() => {
      //     // 用户点击取消，不执行任何操作
      //     this.$message({
      //       type: 'info',
      //       message: '已取消提交'
      //     });
      //   });
      // } else {
      // 如果勾选了供应商付，直接执行提交逻辑
      this.submitBatchFormLogic();
      // }
    },
    /** 分批下单确认按钮 */
    submitBatchFormLogic() {
      if (this.batchOrderProductList.length === 0) {
        this.$modal
          .confirm("您还未选择该计划的产品？是否需要重新选择产品？")
          .then(() => {})
          .catch(() => {
            this.openBatch = false;
          });
      } else {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            // // 1. 检查所有产品的货币单位是否一致
            // const uniqueMonetaryIds = new Set(this.batchOrderProductList.map(product => product.monetaryId));
            // if (uniqueMonetaryIds.size > 1) {
            //   this.$modal.msgError("产品列表中的货币单位不一致，请统一货币单位！");
            //   return;
            // }
            // // 针对每个产品的非空校验
            // for (let i = 0; i < this.batchOrderProductList.length; i++) {
            //   const product = this.batchOrderProductList[i];

            //   // 单价非空校验
            //   if (product.productPrice === undefined || product.productPrice === null || product.productPrice === "") {
            //     this.$modal.msgError(`产品 ${product.sku} 的单价不能为空！`);
            //     return;
            //   }
            //   // 可转数量非空校验
            //   if (product.transferableNumber === undefined || product.transferableNumber === null || product.transferableNumber === "") {
            //     this.$modal.msgError(`产品 ${product.sku} 的可转数量不能为空！`);
            //     return;
            //   }
            //   // 税率非空校验
            //   if (product.rate === undefined || product.rate === null || product.rate === "") {
            //     this.$modal.msgError(`产品 ${product.sku} 的税率不能为空！`);
            //     return;
            //   }
            //   // 货币单位非空校验
            //   if (product.monetaryId === undefined || product.monetaryId === null || product.monetaryId === "") {
            //     this.$modal.msgError(`产品 ${product.sku} 的货币单位不能为空！`);
            //     return;
            //   }
            //   // 汇率非空校验
            //   if (product.currency === undefined || product.currency === null || product.currency === "") {
            //     this.$modal.msgError(`产品 ${product.sku} 的汇率不能为空！`);
            //     return;
            //   }
            //   // 如果未勾选供应商付，则运费必须非空校验
            //   if (!product.flag && (product.freight === undefined || product.freight === null || product.freight === "")) {
            //     this.$modal.msgError(`产品 ${product.sku} 的运费不能为空！`);
            //     return;
            //   }
            //   // 供应商非空校验
            //   if (product.vendorId === undefined || product.vendorId === null || product.vendorId === "") {
            //     this.$modal.msgError(`产品 ${product.sku} 的供应商不能为空！`);
            //     return;
            //   }
            //   // 交付时间非空校验
            //   if (product.deliveryTime === undefined || product.deliveryTime === null || product.deliveryTime === "") {
            //     this.$modal.msgError(`产品 ${product.sku} 的交付时间不能为空！`);
            //     return;
            //   }
            // }

            // // 针对每个产品校验汇率和运费（基于每行数据）
            // for (let i = 0; i < this.batchOrderProductList.length; i++) {
            //   const product = this.batchOrderProductList[i];
            //   // 校验汇率
            //   if (!product.currency) {
            //     this.$modal.msgError(`产品 ${product.sku} 的汇率不能为空！`);
            //     return;
            //   }
            //   const currencyValue = parseFloat(product.currency);
            //   if (isNaN(currencyValue) || currencyValue <= 0) {
            //     this.$modal.msgError(`产品 ${product.sku} 的汇率输入无效，请输入有效的数字！`);
            //     return;
            //   }
            //   // 当供应商不付时，对运费进行校验（flag 为 false 或未选中）
            //   if (!product.flag) {
            //     if (product.freight === undefined || product.freight === null || product.freight === "") {
            //       this.$modal.msgError(`产品 ${product.sku} 的运费不能为空！`);
            //       return;
            //     }
            //     const freightValue = parseFloat(product.freight);
            //     if (isNaN(freightValue) || freightValue < 0) {
            //       this.$modal.msgError(`产品 ${product.sku} 的运费输入无效，请输入有效的数字！`);
            //       return;
            //     }
            //   }
            // }

            // // 新增：校验同一供应商的产品是否存在供应商付设置不一致
            // const vendorGroups = {};
            // this.batchOrderProductList.forEach(product => {
            //   // 按供应商分组
            //   let vendor = product.vendorId;
            //   if (!vendorGroups[vendor]) {
            //     vendorGroups[vendor] = [];
            //   }
            //   vendorGroups[vendor].push(product);
            // });
            // for (const vendor in vendorGroups) {
            //   const group = vendorGroups[vendor];
            //   const hasSupplierPaid = group.some(product => product.flag === true);
            //   const hasNotSupplierPaid = group.some(product => !product.flag);
            //   if (hasSupplierPaid && hasNotSupplierPaid) {
            //     this.$modal.msgError(`供应商为 ${vendor} 的产品存在供应商付设置不一致，请统一设置！`);
            //     return;
            //   }
            // }

            // // 存储有问题的产品
            // let exceededProducts = [];
            // let invalidProducts = [];
            // let emptyTransferableProducts = [];
            // let procuredFlag = true; // 初始化标志位

            // // 检查每个产品的可转数量是否超出采购数量、为零或未填写
            // for (let i = 0; i < this.batchOrderProductList.length; i++) {
            //   const product = this.batchOrderProductList[i];
            //   const totalTurnedNumber =
            //     parseInt(product.turnedNumber || 0) +
            //     parseInt(product.transferableNumber || 0);

            //   // 验证 transferableNumber 是否未填写或为 NaN
            //   if (
            //     product.transferableNumber === undefined ||
            //     product.transferableNumber === null ||
            //     product.transferableNumber === "" ||
            //     isNaN(parseInt(product.transferableNumber))
            //   ) {
            //     emptyTransferableProducts.push(product);
            //     procuredFlag = false;
            //     continue; // 跳过后续验证，进入下一个循环
            //   }

            //   // 验证已采购数量不能小于等于 0
            //   if (parseInt(product.transferableNumber) <= 0) {
            //     invalidProducts.push(product);
            //     procuredFlag = false;
            //   }

            //   // 验证是否超出数量
            //   if (totalTurnedNumber > parseInt(product.number)) {
            //     exceededProducts.push(product); // 将超出数量的产品添加到数组中
            //     procuredFlag = false; // 设置标志位为 false
            //   }
            // }

            // // 如果存在未填写可转数量的产品，提示警告信息
            // if (emptyTransferableProducts.length > 0) {
            //   let proNoList = emptyTransferableProducts.map((product) => product.sku).join(","); // 获取未填写的产品编号列表
            //   this.$modal.msgWarning("产品sku " + proNoList + " 的可转数量未填写！");
            // }

            // // 如果存在采购数量为 0 或负数的产品，提示警告信息
            // if (invalidProducts.length > 0) {
            //   let proNoList = invalidProducts.map((product) => product.proNo).join(","); // 获取非法数量的产品编号列表
            //   this.$modal.msgWarning("产品sku " + proNoList + " 的可转数量必须大于 0！");
            // }

            // // 如果存在超出数量的产品，提示警告信息
            // if (exceededProducts.length > 0) {
            //   let proNoList = exceededProducts.map((product) => product.proNo).join(","); // 获取超出数量的产品编号列表
            //   this.$modal.msgWarning("产品sku " + proNoList + " 超出可采购数量范围！");
            // }

            // 调用统一的产品校验方法
            if (
              !this.validateProcurementQuantities(this.batchOrderProductList)
            ) {
              return;
            }
            // 更新 form 中的产品列表
            this.form.batchOrderProductList = this.batchOrderProductList;
            
            // 插入采购订单
            getInsertProcuredOrders(this.form).then(() => {
              this.$modal.msgSuccess("采购操作成功！");
              this.open = false;
              this.openBatch = false;
              this.getList(); // 刷新列表
            });
          }
        });
      }
    },

    // 选择销售计划
    handleSalesPlan() {
      this.titleSalesPlan = "选择销售计划";
      this.openSalesPlan = true;
      this.getPlanList();
    },
    /** 查询销售中心列表 */
    getPlanList() {
      this.loading = false;
      getListPlan(this.queryParamPlan).then((response) => {
        this.planListIndex = response.rows;
        this.totalPlan = response.total;
      });
    },
    /** 选择 */
    handlePlan(row) {
      this.form.salesPlanNumber = row.planNumber;
      this.form.salesPlanId = row.id;
      this.queryParamProduct.salesPlanId = row.id;
      this.openSalesPlan = false;
    },
    // 打开详情窗口的方法
    handleDetails(row) {
      this.resetForm("ordersQueryForm");
      this.OrderList = [];
      let planId = row.planId;
      this.ordersQuery.planId = planId;
      //查询当前采购计划相关数据
      getPlan(planId).then((response) => {
        this.form.currency = 1; // 设置汇率为1
        this.currencyDisabled = true; // 禁用汇率输入框
        this.detailForm = response.data;
        this.openDetail = true; // 打开详情窗口
      });

      //查询采购计划中的订单详细数据
      getOrderDetails(this.ordersQuery).then((response) => {
        this.OrderList = response.rows;
        this.orderTotal = response.total;
      });
    },
    resetOrdersQuery() {
      /** 重置按钮操作 */
      this.resetForm("ordersQueryForm");
      this.handleOrderQuery();
    },
    handleOrderQuery() {
      this.OrderList = [];
      getOrderDetails(this.ordersQuery).then((response) => {
        this.OrderList = response.rows;
        this.orderTotal = response.total;
      });
    },
    //弹出审核中
    underReview() {
      this.openAudit = true;
      this.audit = "审批管理";
      this.activeTab = "toAudit";
      this.loadData();
    },
    cancelTreat() {
      this.openAudit = false;
    },

    //--------审核模板开始-----------
    loadData() {
      const tab = this.activeTab;
      const { pageNum, pageSize } = this.pageParams[tab];

      if (tab === "toAudit") {
        const params = {
          planStatus: 0,
          reviewerUserId: this.userId,
          userName: this.nickName,
          pageNum,
          pageSize,
        };
        getPlanWaitProcessList(params).then((res) => {
          this.tabData.toAudit = res.rows;
          this.tabTotals.toAudit = res.total;
        });
      }

      if (tab === "audited") {
        const params = {
          userId: this.userId,
          userName: this.nickNameReviewed,
          pageNum,
          pageSize,
        };
        getPlanReadyProcessList(params).then((res) => {
          this.tabData.audited = res.rows;
          this.tabTotals.audited = res.total;
        });
      }

      if (tab === "myAudit") {
        const params = {
          userId: this.userId,
          pageNum,
          pageSize,
        };
        getPlanMyProcessList(params).then((res) => {
          this.tabData.myAudit = res.rows;
          this.tabTotals.myAudit = res.total;
        });
      }
    },
    handleTabClick(tab) {
      this.pageParams[tab.name].pageNum = 1;
      this.activeTab = tab.name;
      this.loadData();
    },

    handlePagination({ page, limit }) {
      this.pageParams[this.activeTab].pageNum = page;
      this.pageParams[this.activeTab].pageSize = limit;
      this.loadData();
    },
    //待我审核
    getAudit() {
      (this.waitProcess.planStatus = 0),
        (this.waitProcess.reviewerUserId = this.userId);
      this.waitProcess.userName = this.nickName;
      getPlanWaitProcessList(this.waitProcess).then((response) => {
        this.auditLength = response.total;
        this.auditData = response.rows;
      });
    },
    /** 查询自己已审批的数据 */
    getSelectPlanReviewed() {
      this.readyProcess.userId = this.userId;
      this.readyProcess.userName = this.nickNameReviewed;
      getPlanReadyProcessList(this.readyProcess).then((response) => {
        this.planReviewedLenght = response.total;
        this.planReviewed = response.rows;
      });
    },
    /** 查询自己发送的审批数据 */
    getPlanInitiated() {
      this.myProcess.userId = this.userId;
      getPlanMyProcessList(this.myProcess).then((response) => {
        this.planInitiatedLenght = response.total;
        this.planInitiated = response.rows;
      });
    },
    borderTrigger(data) {
      this.drawer = true;
      this.drawerValue = data;
      getPlanProcessList(data.planId).then((r) => {
        this.planProcessData = r.data;
      });
    },
    //查审核日志
    planProcessLog(row) {
      this.openLog = true;
      this.logParam.procuredPlanId = row.planId;
      this.getPlanProcessLogList();
    },
    //查询所有的申请记录
    getPlanProcessLogList() {
      this.loading = true;
      selectPlanProcessLogList(this.logParam).then((response) => {
        this.PlanProcessLogList = response.rows;
        this.logTotals = response.rows.length;
        this.loading = false;
      });
    },
    cancelPlanProcessLog() {
      this.openLog = false;
    },
    /** 审批同意按钮 */
    async approvePlan(planId, planProcessStatus) {
      // 避免重复提交
      if (this.isSubmitting) return;

      this.approvalProcess.procuredPlanId = planId;
      this.approvalProcess.processStatus = planProcessStatus;
      this.approvalProcess.processRemark = this.planProcessRemark;
      try {
        await updatePlanProcessStatus(this.approvalProcess);
        let title = "同意审批";
        if (planProcessStatus != 1) {
          title = "拒绝审批";
        }
        this.$modal.msgSuccess(title);
        this.drawer = false;
        this.loadData();
        this.getList();
      } catch (error) {
        this.$modal.msgError("提交审批中中，请勿重复提交");
      } finally {
        this.isSubmitting = false; // 请求完成后解锁
      }
    },
    /** 审批拒绝按钮 */
    rejectPlan(planId, planProcessStatus) {
      if (!this.planProcessRemark) {
        this.$message.error("请填写备注");
        return;
      }
      this.approvePlan(planId, planProcessStatus);
    },
    //--------审核模板结束-----------

    // 判断行是否可选
    isRowSelectable(row, index) {
      return row.transferableNumber > 0;
    },
    getRowClass(row) {
      return row.transferableNumber <= 0 ? "disabled-row" : "";
    },

    //撤回
    handleAudit() {
      this.revoke.revokeRemark = ""; // 清空备注
      const nickName = this.$store.state.user.nickName;
      if (nickName != this.checkUserName) {
        this.$message.error(
          "当前用户【" +
            nickName +
            "】，与采购计划创建人【" +
            this.checkUserName +
            "】不匹配，请重新选择"
        );
        return;
      }
      this.dialogVisible = true;
      this.openRevoke = true;
    },
    closeRevoke() {
      this.dialogVisible = false;
      this.openRevoke = false;
    },
    // 点击确定，提交撤回操作
    confirmWithdraw() {
      if (!this.revoke.revokeRemark.trim()) {
        this.$message.warning("请输入撤回备注");
        return;
      }
      const planId = this.checkPlanId;
      this.revoke.planId = planId;
      let originalPath = this.$route.path; // 当前路径
      let componentPath = formatPath(originalPath);
      revokeProcuredPlan(this.revoke, componentPath).then((r) => {
        this.$message.success("撤回成功");
        this.getList();
        this.closeRevoke();
      });
    },
    // 货币单位改变时触发
    handleCurrencyChangeRow(row) {
      // 如果选择的货币单位为 CNY，保持汇率为 1 并禁用输入
      if (row.monetaryId == 1 || row.monetaryId == 3) {
        row.currency = 1;
        row.currencyDisabled = true;
      } else {
        // 其他货币单位时解除禁用，让用户可修改汇率
        row.currencyDisabled = false;
      }
      // 汇率变化时重新计算金额
      this.calculateAmount(row);
    },
    // 汇率、数量、单价发生变化时触发
    handleRateChangeRow(row) {
      this.calculateAmount(row);
    },
    // 金额计算：数量 * 单价 * 汇率
    calculateAmount(row) {
      const number = Number(row.transferableNumber) || 0;
      const productPrice = Number(row.productPrice) || 0;
      const currency = Number(row.currency) || 0;
      console.log("汇率", JSON.stringify(currency, null, 2));
      const rate = parseFloat(row.rate || 0) / 100; // 转换税率为小数
      console.log("税率", JSON.stringify(rate, null, 2));
      // 计算金额
      row.amount = number * productPrice * currency;
      console.log("计算金额", JSON.stringify(row.amount, null, 2));
      // 计算税额 (价格 * 数量 * 汇率 * 税率)
      row.tax = productPrice * number * currency * rate;
      console.log("计算税额", JSON.stringify(row.tax, null, 2));
      // 计算含税金额
      row.taxIncluded = row.amount + row.tax;
      console.log("计算含税金额", JSON.stringify(row.taxIncluded, null, 2));
    },
    supplierTypeChange() {
      this.batchOrderProductList = [];
    },
    // 运费输入框失去焦点时触发，进行运费平摊
    handleFreightBlur(row) {
      // 如果当前行被禁用，则不做处理
      if (this.isDisabledByVendor(row)) {
        return;
      }
      // 转换运费为数字
      let freightVal = parseFloat(row.freight);

      // 筛选出同一供应商的所有产品
      const sameVendorProducts = this.tbProcuredProductList.filter(
        (item) => item.vendorId === row.vendorId
      );

      if (isNaN(freightVal)) {
        // 对每个产品的运费进行清空
        sameVendorProducts.forEach((item) => {
          item.freight = null;
        });
        return;
      }

      // 计算所有产品的数量总和，假设数量字段为 number
      const totalQuantity = sameVendorProducts.reduce(
        (sum, item) => sum + (Number(item.number) || 0),
        0
      );
      if (totalQuantity === 0) return;
      // 对每个产品按比例分摊运费，结果保留两位小数
      sameVendorProducts.forEach((item) => {
        let allocated =
          (freightVal * (Number(item.number) || 0)) / totalQuantity;
        allocated = parseFloat(allocated.toFixed(4)); // 四舍五入保留两位小数
        item.freight = allocated;
      });
    },
    handleViewProducts(row) {
      this.loading = true;
      // 如果需要验证其他条件可以在这里添加逻辑
      const planId = row.planId;
      if (!planId) {
        this.$message.warning("无效的采购计划ID");
        return;
      }
      this.viewMode = true;
      getPlanProducts(planId)
        .then((response) => {
          this.open = true;
          this.loading = false;
          this.title = "查看采购计划";
          this.form = response.data;
          this.$nextTick(() => {
            this.tbProcuredProductList = response.data.tbProcuredProductList;
          });
        })
        .catch((error) => {
          this.loading = false;
          this.$message.error("获取产品数据失败，请稍后重试");
        });
    },
    // span-method 用于合并单元格：除了 GTIN 列之外，其它列均合并显示
    tableSpanMethod({ row, column, rowIndex }) {
      // 指定不合并的列（例如 GTIN 列），其他列进行合并
      const unMergeColumns = ["gtin", "number", "freight"];
      if (!unMergeColumns.includes(column.property)) {
        const sku = row.sku;
        if (sku && this.skuGroups && this.skuGroups[sku]) {
          const group = this.skuGroups[sku];
          // 如果当前行是该 sku 分组中的第一行，则返回合并行数，否则返回 0
          if (rowIndex === group.start) {
            return {
              rowspan: group.count,
              colspan: 1,
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0,
            };
          }
        }
      }
      return {
        rowspan: 1,
        colspan: 1,
      };
    },
    /**
     * 分批下单的单元格合并方法，根据 sku 分组合并相同 sku 的行，
     * 对于不需要合并的列（例如 'gtin', 'number', 'freight'）则直接返回默认值。
     *
     * @param {Object} param0 - 包含当前单元格对应的 row, column, rowIndex 等信息
     * @returns {Object} 返回一个对象，指定当前单元格的 rowspan 和 colspan
     */
    batchSpanMethod({ row, column, rowIndex }) {
      // 定义不需要合并单元格的字段列表
      const unMergeColumns = [
        "gtin",
        "number",
        "freight",
        "turnedNumber",
        "transferableNumber",
      ];
      if (unMergeColumns.includes(column.property)) {
        return { rowspan: 1, colspan: 1 };
      }

      // 这里使用分批下单的数据源
      const data = this.batchOrderProductList;

      // 如果当前行的 sku 与上一行相同，则表明该单元格不是合并区域的开始，直接返回合并数为 0
      if (rowIndex > 0 && data[rowIndex - 1].sku === row.sku) {
        return { rowspan: 0, colspan: 0 };
      }

      // 计算连续具有相同 sku 的行数
      let rowspan = 1;
      for (let i = rowIndex + 1; i < data.length; i++) {
        if (data[i].sku === row.sku) {
          rowspan++;
        } else {
          break;
        }
      }

      // 返回合并规则：当前单元格横跨 1 列，纵跨 rowspan 行
      return { rowspan, colspan: 1 };
    },
  },
};
</script>

<style scoped>
.zero-quantity {
  color: #909399;
}

/* 可以在行级别添加整行禁用样式 */
.el-table__row.disabled-row {
  opacity: 0.6;
  background-color: #f5f7fa;
}

.zz {
  padding: 0px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}

.custom-input .el-input__inner {
  border: none;
  background-color: transparent;
  text-align: left;
}

.custom-input .el-input__inner:focus {
  border: 1px solid #dcdfe6;
  background-color: white;
}

/* --------审核模板开始----------- */
.auditStyle {
  width: 1166px;
}

.show-frame {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100%;
  height: 70px;
  margin-bottom: 10px;
}

.show-frame-container {
  overflow: auto;
  height: 560px;
  /* 设置容器的高度 */
}

.singleHanded-css {
  display: block;
  margin-left: 54px;
  margin-top: -66px;
}

.planNumber-css {
  display: block;
  margin-top: -50px;
  margin-left: 335px;
}

.mannerName-css {
  display: block;
  margin-top: 11px;
  margin-left: 335px;
}

.planProcessTime-css {
  display: block;
  margin-top: -50px;
  margin-left: 585px;
}

.planProcessStatus-css {
  display: flex;
  /* 使用 flexbox 布局 */
  align-items: center;
  /* 垂直居中 */
  gap: 15px;
  /* 控制子元素之间的间距 */
  margin-top: 5px;
  margin-left: 585px;
  /* 可调整 */
}

.shipTime-css {
  display: block;
  margin-top: -50px;
  margin-left: 994px;
}

.shipTimeReady-css {
  display: block;
  margin-top: -58px;
  margin-left: 814px;
}

.shipAmoutMy-css {
  display: block;
  margin-top: -50px;
  margin-left: 644px;
}

.planStatus-css {
  display: flex;
  margin-top: 10px;
  margin-left: 814px;
}

.planStatusMy-css {
  display: flex;
  margin-top: 10px;
  margin-left: 644px;
}

.center-title .el-drawer__title {
  text-align: center;
}

.drawerValueUserImg {
  display: block;
}

.drawerValueSingleHanded {
  display: block;
  margin-top: -65px;
  margin-left: 96px;
}

.drawerValuePlanStatus {
  display: block;
  margin-top: -13px;
  margin-left: 98px;
}

.el-descriptions--mini:not(.is-bordered) .el-descriptions-item__cell {
  padding-bottom: 9px;
  font-size: 13px;
}

.margin-top {
  display: block;
  margin-top: 16px;
  margin-left: 20px;
}

.margin-top1 {
  display: block;
  margin-top: -47px;
  margin-left: 89px;
}

hr {
  border-color: #0000;
  height: 7px;
  background-color: #f3f3f3;
}

.el-descriptions-item__label.has-colon::after {
  content: ":";
  position: relative;
  top: -0.5px;
  display: none;
}

.sponsor {
  font-size: 14px;
  display: block;
  margin-top: -41px;
  margin-left: 96px;
}

.sponsor-name {
  font-size: 12px;
  display: block;
  margin-top: 4px;
  margin-left: 96px;
  color: #6f7174;
}

.sponsor-time {
  font-size: 12px;
  display: block;
  margin-top: -34px;
  margin-left: 439px;
  color: #6f7174;
}

.postUserDept-css {
  display: block;
  margin-top: 30px;
  height: 36px;
}

.postUserDept-postName {
  font-size: 12px;
  display: block;
  margin-top: 3px;
  margin-left: 439px;
  color: #6f7174;
}

.block {
  display: block;
  margin-left: 19px;
  margin-top: 55px;
}

.ccPerson {
  font-size: 14px;
  display: block;
  margin-top: -51px;
  margin-left: 96px;
}

.approval {
  position: fixed;
  right: 28px;
  bottom: 20px;
}

.approvalProcess-container {
  display: flex;
  flex-wrap: nowrap;
  margin-left: 78px;
  margin-top: 18px;
}

.approvalProcess-image {
  float: left;
  margin-right: 3px;
  /* 调整图片之间的间距 */
}

.approvalProcess-size {
  font-size: 12px;
  display: block;
  color: #6f7174;
  margin-left: 15px;
  margin-top: 10px;
}

._scroll-container {
  margin-top: 45px;
  height: 250px;
  max-height: 300px;
  /* 设置最大高度 */
  overflow-y: auto;
  /* 垂直滚动 */
  border: 2px solid #ccc;
  /* 边框可选 */
}

.processRemark-input {
  width: 70%;
  /* 占满可用宽度 */
  margin-bottom: 20px;
  /* 与按钮组的间距 */
}

.button-group {
  display: flex;
  float: right;
  transform: translateX(-30%);
  /* 修正因right的偏移 */
  gap: 50px;
  /* 按钮之间的间距 */
}

.approval {
  position: sticky;
  bottom: 20px;
  flex-direction: column;
  align-items: flex-start;
  /* 靠左对齐 */
  margin-top: 10px;
}

.plan-size {
  display: block;
  transform: translateY(-60px);
  margin-left: 54px;
}

.h1,
.h2,
.h3,
.h4,
.h5,
.h6,
h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: inherit;
  font-weight: 500;
  line-height: 1.1;
  color: black;
  font-weight: bold;
}

.sponsor {
  font-size: 14px;
  display: block;
  margin-top: -41px;
  margin-left: 96px;
}

.sponsor-name {
  font-size: 12px;
  display: block;
  margin-top: 4px;
  margin-left: 96px;
  color: #6f7174;
}

.sponsor-time {
  font-size: 12px;
  display: block;
  margin-top: -34px;
  margin-left: 439px;
  color: #6f7174;
}

/* --------审核模板结束----------- */

/* Sin la palabra 'scoped' para que afecte a todos los componentes */
/deep/ .el-table .el-table__row.disabled-row {
  background-color: #c7c7c7 !important;
  opacity: 0.6 !important;
}
/* 
/deep/ .el-table .el-table__row.disabled-row td {
  background-color: #949494 !important;
  color: #ffffff !important;
} */

.el-table .disabled-row .el-input input,
.el-table .disabled-row .el-select .el-input__inner,
.el-table .disabled-row .el-checkbox,
.el-table .disabled-row .el-date-editor,
.el-table .disabled-row .el-textarea textarea {
  background-color: #f5f7fa !important;
  color: #c0c4cc !important;
  cursor: not-allowed !important;
  pointer-events: none !important;
}
</style>
